I am working with Unsplash API to get Images. When I send the request for an Image, part of the answer is the Image URL which looks like this:
https://images.unsplash.com/photo-1535159530326-d7bf54bfb24e?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjM1NDkzfQ&s
I was able to make this URL a BitmapImage and make it an Image Source in the app UI. But I was not able to download it to make it a StorageFile.
How can I download the image from this kind of URL and/or make it a StorageFile?
The following code will download the file into local storage, and then give you a Uri that you can use to set the Image Source:
private async Task<String> DownloadImage(string url, String fileName)
{
const String imagesSubdirectory = "DownloadedImages";
var rootFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(imagesSubdirectory, CreationCollisionOption.OpenIfExists);
var storageFile = await rootFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (HttpClient client = new HttpClient())
{
byte[] buffer = await client.GetByteArrayAsync(url);
using (Stream stream = await storageFile.OpenStreamForWriteAsync())
stream.Write(buffer, 0, buffer.Length);
}
// Use this path to load image
String newPath = String.Format("ms-appdata:///local/{0}/{1}", imagesSubdirectory, fileName);
return newPath;
}
// Here is an example of how to use the new DownloadImage() method
private async void Button_Download(object sender, RoutedEventArgs e)
{
var uniqueFileName = $#"{Guid.NewGuid()}.jpg";
String newPath = await DownloadImage("https://images.unsplash.com/photo-1535159530326-d7bf54bfb24e?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjM1NDkzfQ&s=6dbf8e03a25f469d0f845992e6b2eb9e",
uniqueFileName);
myImage.Source = new BitmapImage(new Uri(newPath));
}
Related
I'm using a post call to get a byte stream with all the data for a PDF, then I want to open the PDF using the default program in Android. Will later do for iOS.
Here's my code:
async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
{
Publication p = (Publication)e.SelectedItem;
Debug.WriteLine(p);
if (p.folderID.Equals("-1"))
{
using (Stream respStream = await post(p.docNum))
{
byte[] buffer = new byte[respStream.Length];
respStream.Read(buffer, 0, buffer.Length);
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
File.WriteAllBytes(path + "foo.pdf", buffer);
Device.OpenUri(new Uri(path + "foo.pdf"));
}
}
else
{
await Navigation.PushAsync(new PublicationsPage(p.folderID));
}
}
private async Task<Stream> post(string id)
{
Dictionary<string, string> dir = new Dictionary<string, string>();
dir.Add("LoginID", App.user.login_id);
dir.Add("docID", id);
var jsonReq = JsonConvert.SerializeObject(dir);
Debug.WriteLine("req: " + (String)jsonReq);
var content = new StringContent(jsonReq, Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, content);
var responseStream = await response.Content.ReadAsStreamAsync();
return responseStream;
}
What I have now downloads the pdf as a byte stream then makes a window pop up then close. What should I do to fix? I'd rather not pay for any packages and ideally I'd like to have it prompt for what program to open with.
The file system is different between Ios and Android. So, you need use DependencyService to save and load the PDF file on different platform.
Thanks #B.6242, in this issue, #B.6242 has implemented it in both Android and Ios with DependencyService, you can refer to it.
Here is an issue about how to use the file system on different platforms.
Got it to work by following this: https://developer.xamarin.com/recipes/cross-platform/xamarin-forms/controls/display-pdf/
In the code above, change OnItemSelected to this, where PDFViewPage uses the customWebView described in the above link:
async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
{
Publication p = (Publication)e.SelectedItem;
Debug.WriteLine(p);
if (p.folderID.Equals("-1"))
{
using (Stream respStream = await post(p.docNum))
{
byte[] buffer = new byte[respStream.Length];
respStream.Read(buffer, 0, buffer.Length);
string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
File.WriteAllBytes(path + "foo.pdf", buffer);
await Navigation.PushAsync(new PDFViewPage(path + "foo.pdf"));
//Device.OpenUri(new Uri(path + "foo.pdf"));
}
}
else
{
await Navigation.PushAsync(new PublicationsPage(p.folderID));
}
}
It's my first time developing on UWP and I can't add an image into Mysql database using PHP and I must add its' path in the database.
I can't use sqlite or any other database as my collegues started already using Mysql.
Can anyone please help me or give an example
I wouLd really appreciate your help (i'm stuck here )
So, here is my UWP code that I used to upload the chosen image from my gallery
private Stream stream = new MemoryStream();
private CancellationTokenSource cts;
public MainPage()
{
this.InitializeComponent();
}
private async void buttonUpload_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker open = new FileOpenPicker();
open.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
open.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
open.FileTypeFilter.Clear();
open.FileTypeFilter.Add(".bmp");
open.FileTypeFilter.Add(".png");
open.FileTypeFilter.Add(".jpeg");
open.FileTypeFilter.Add(".jpg");
// Open a stream for the selected file
StorageFile file = await open.PickSingleFileAsync();
// Ensure a file was selected
if (file != null)
{
// Ensure the stream is disposed once the image is loaded
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
{
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
fileStream.AsStream().CopyTo(stream);
img.Source = bitmapImage;
}
}
}
private async void submit_Click(object sender, RoutedEventArgs e)
{
Uri uri = new Uri("http://localhost/mydatabase/add.php");
HttpClient client = new HttpClient();
HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream());
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);
request.Content = streamContent;
HttpResponseMessage response = await client.PostAsync(uri, streamContent).AsTask(cts.Token);
`
and here is the php i'm using
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$UserName = $_POST['UserName'];
$UserImage = $_POST['UserImage'];
require_once('conn.php');
$sql ="SELECT UserId FROM user";
$res = mysqli_query($connect,$sql);
$UserId =0 ;
while($row = mysqli_fetch_array($res)){
$UserId = $row['UserId'];
$UserId = $UserId+1;
}
$path = "UserImage/$UserId.png";
$actualpath = "http://localhost/mydatabase/$path";
$sql = "INSERT INTO user (UserId,UserName,UserImage) VALUES ('$UserId','$UserName','$actualpath')";
if(mysqli_query($connect,$sql)){
file_put_contents($path,base64_decode($UserImage));
echo "Successfully Uploaded";
}
mysqli_close($connect);
}else{
echo "Error";
}
?>
And all what i get is empty images in the folder I created ... apparently I have a problem after uploading the image from the UWP, but I'm not sure about that.
Read the file using PHP and insert that into the database.
Keep in mind, the bigger the image the longer the string.
$data = file_get_contents('/pics/item.png');
return $data;
This would return the data(from the picture)
I'm working on windows phone 8.1 application. I have different pictures locally in app and displaying those pictures in list view. Now select one picture id and pass it to detail screen, where I have to save that file .
My detail.Xaml screen contain image control named as Imaged.
I got image on detail page and press image save button. I'm using this Sample app https://code.msdn.microsoft.com/windowsapps/Save-Edited-Picture-16d910c4/sourcecode?fileId=119937&pathId=946309183 "Sample"
My detail page Code is here.
string tempimg;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var imagePath = e.Parameter as string;
imaged.Source = new BitmapImage(new Uri(imagePath, UriKind.RelativeOrAbsolute));
tempimg = imagePath;
}
My SaveImage button code is here.
if (tempimg == null)
return;
// WriteableBitmap abc = new WriteableBitmap(400, 400);
string filename = "Image-" + DateTime.Now.ToFileTime() + ".jpeg";
// await SaveWriteableBitmapAsJpeg(img, filename);
Blockquote
await SaveWriteableBitmapAsJpeg(tempimg, filename);
private static async Task SaveWriteableBitmapAsJpeg(WriteableBitmap bmp, string fileName)
{
// Create file in Pictures library and write jpeg to it
var outputFile = await KnownFolders.CameraRoll.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (var writeStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
{
await EncodeWriteableBitmap(bmp, writeStream, BitmapEncoder.JpegEncoderId);
}
}
private static async Task EncodeWriteableBitmap(WriteableBitmap bmp, IRandomAccessStream writeStream, Guid encoderId)
{
// Copy buffer to pixels
byte[] pixels;
using (var stream = bmp.PixelBuffer.AsStream())
{
pixels = new byte[(uint)stream.Length];
await stream.ReadAsync(pixels, 0, pixels.Length);
}
// Encode pixels into stream
var encoder = await BitmapEncoder.CreateAsync(encoderId, writeStream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied,
(uint)bmp.PixelWidth, (uint)bmp.PixelHeight,
96, 96, pixels);
await encoder.FlushAsync();
}
My this function "await SaveWriteableBitmapAsJpeg(tempimg, filename);" creates a problem. I just have the image source while that require the writeablebitmap. I just want to save image and not able to proceed from here. let me know the exact solution or problem.
How do I download and store a jpeg image from the internet in a Windows Store App with Windows.Web.Http?
The problem that I am facing is that I don't know what Get…Async and Write…Async method I must use for an image? It is very different with files, than with strings.
Only Windows.Web.Http!
No third-party solutions!
If you suggest something else, please use the comment section, not the answer. Thank you!
…
using Windows.Storage;
using Windows.Web.Http;
Uri uri = new Uri("http://image.tmdb.org/t/p/w300/" + posterPath);
HttpClient httpClient = new HttpClient();
// I guess I need to use one of the Get...Async methods?
var image = await httpClient.Get…Async(uri);
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFolder cachedPostersFolder = await localFolder.CreateFolderAsync("cached posters", CreationCollisionOption.OpenIfExists);
StorageFile posterFile = await cachedPostersFolder.CreateFileAsync(posterPath, CreationCollisionOption.ReplaceExisting);
// I guess I need to use one of the Write...Async methods?
await FileIO.Write…Async(posterFile, image);
You can get a buffer using the GetBufferAsync method and then call the FileIO.WriteBufferAsync to write the buffer to a file:
Uri uri = new Uri("http://i.stack.imgur.com/ZfLdV.png?s=128&g=1");
string fileName = "daniel2.png";
StorageFile destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
fileName, CreationCollisionOption.GenerateUniqueName);
HttpClient client = new HttpClient();
var buffer = await client.GetBufferAsync(uri);
await Windows.Storage.FileIO.WriteBufferAsync(destinationFile, buffer);
image1.Source = new BitmapImage(new Uri("http://www.image.com/image.jpg", UriKind.RelativeOrAbsolute));
using (var mediaLibrary = new MediaLibrary())
{
using (var stream = new MemoryStream())
{
var fileName = string.Format("Gs{0}.jpg", Guid.NewGuid());
bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
var picture = mediaLibrary.SavePicture(fileName, stream);
if (picture.Name.Contains(fileName)) return true;
}
}
This is a similar answer to John's, however in WP8.1 you can't use GetBufferAsync. Instead you can use GetStreamAsync in the way that I have:
Uri uri = new Uri(UriString);
string fileName = p4.IconLocation;
HttpClient client = new HttpClient();
var streamImage = await client.GetStreamAsync(uri);
await SaveToLocalFolderAsync(streamImage, fileName);
using the function:
public async Task SaveToLocalFolderAsync(Stream file, string fileName)
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (Stream outputStream = await storageFile.OpenStreamForWriteAsync())
{
await file.CopyToAsync(outputStream);
}
}
I was wondering how I can download an MP4 video file from a URI and save it to the media library on Windows Phone 8.1.
It would be great if it worked in a Universal App - but it doesn't have to.
I found this code to save an image to the camera roll - do I go the same way about this with an *.mp4 to save it to the video library? And can I just hand off a download stream (not sure if that makes sense) to that function?
StorageFolder testFolder = await StorageFolder.GetFolderFromPathAsync(#"C:\test");
StorageFile sourceFile = await testFolder.GetFileAsync("TestImage.jpg");
StorageFile destinationFile = await KnownFolders.CameraRoll.CreateFileAsync("MyTestImage.jpg");
using (var sourceStream = await sourceFile.OpenReadAsync())
{
using (var sourceInputStream = sourceStream.GetInputStreamAt(0))
{
using (var destinationStream = await destinationFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (var destinationOutputStream = destinationStream.GetOutputStreamAt(0))
{
await RandomAccessStream.CopyAndCloseAsync(sourceInputStream, destinationStream);
}
}
}
}
So I finally figured it out, this is what my code looks like:
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var file = await response.Content.ReadAsByteArrayAsync();
StorageFile destinationFile
= await KnownFolders.SavedPictures.CreateFileAsync("file.mp4",
CreationCollisionOption.ReplaceExisting);
Windows.Storage.Streams.IRandomAccessStream stream = await destinationFile.OpenAsync(FileAccessMode.ReadWrite);
IOutputStream output = stream.GetOutputStreamAt(0);
DataWriter writer = new DataWriter(output);
writer.WriteBytes(file);
await writer.StoreAsync();
await output.FlushAsync();
}