WinRt - FileSavePicker, save image from URI to file - c#

I would like to ask how I can save image from stream to file. I have created this FileSavePicker, but I don not know how i can save image from Uri
Thanks
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadLine(); // URi with image
private async void saveClick(object sender, RoutedEventArgs e)
{
var Picker = new FileSavePicker();
Picker.FileTypeChoices.Add("Image", new List<string>() { ".jpg" });
StorageFile file = await Picker.PickSaveFileAsync();
}

I assume you already have downloaded the image into dataStream. If not you can do so with the HttpClient class:
var uri = new Uri("http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo-med.png");
Windows.Web.Http.HttpClient httpClient = new HttpClient();
var stream = await httpClient.GetInputStreamAsync(uri);
Stream dataStream = stream.AsStreamForRead();
You can get a writeable stream to your picked file by calling OpenStreamForWriteAsync on the StorageFile. With two streams you can call CopyTo to copy from the dataStream to the save stream.
var Picker = new FileSavePicker();
Picker.FileTypeChoices.Add("Image", new List<string>() { ".jpg" });
StorageFile file = await Picker.PickSaveFileAsync();
using (Stream saveStream = await file.OpenStreamForWriteAsync())
{
dataStream.Seek(0, SeekOrigin.Begin);
await dataStream.CopyToAsync(saveStream);
}

Related

byte[] upload to mysql blob contains no data

I'm trying to upload a byte array to a mysql column type mediumblob. after the upload I see the blob has a size in kilobytes, however, when I download the file and view it in notepad... it's just empty white space.
here's how I am getting my bytes from an image PNG file:
private async void artworkFileBTN_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".png");
artworkfile = await openPicker.PickSingleFileAsync();
if (artworkfile != null)
{
artworkSet = true;
//var stream = await musicfile.OpenAsync(Windows.Storage.FileAccessMode.Read);
artworkFileBTN.Content = artworkfile.DisplayName;
var stream = await artworkfile.OpenAsync(FileAccessMode.Read);
var streamBytes = await artworkfile.OpenStreamForReadAsync();
var bytes = new byte[(int)streamBytes.Length];
ArtworkRawData =bytes;
}
else
{
//
}
}
can anyone tell me why my array contains only whitespace?
Solved.
byte[] result;
using (Stream streambytes = await artworkfile.OpenStreamForReadAsync())
{
using (var memoryStream = new MemoryStream())
{
streambytes.CopyTo(memoryStream);
result = memoryStream.ToArray();
}
}
ArtworkRawData = result;

C# Get icon from url as System.Drawing.Icon

I'm trying to put icons on a tab. I'm getting the icon from
http://google.com/favicon.ico for now.
I want to get the favicon.ico as System.Drawing.Icon. The original code I'm using is for a normal image, but I need it to be System.Drawing.Icon.
Here's my code so far:
var iconURL = "http://" + url.Host + "/favicon.ico";
System.Drawing.Icon img = null;
WebRequest request = WebRequest.Create(iconURL);
WebResponse response = request.GetResponse();
using (Stream stream = response.GetResponseStream())
{
img = new System.Drawing.Icon(stream);
// then use the image
}
qTabControl1.ActiveTabPage.Icon = img;
This gives me the following error:
You need to copy it to a stream that supports seeking, here is some sample code (using the newer HttpClient and async/await):
async Task<Icon> GetIcon()
{
var httpClient = new HttpClient();
using (var stream = await httpClient.GetStreamAsync(url))
using (var ms = new MemoryStream())
{
stream.CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin); // See https://stackoverflow.com/a/72205381/640195
return new Icon(ms);
}
}

Windows 8 How to open a BitmapImage as a stream?

In a Windows 8 app, how do I convert a BitmapImage to a Stream? I have a List of BitmapImages and I'm going to use that List to upload each image to a server and I need to use a Stream to do that. So is there a way to convert each individual BitmapImage into a Stream?
No, there isn't. You need to track the original sources or use a WriteableBitmap instead.
Retrieve the bitmap image:
public async void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args)
{
if (args.Files.Count > 0)
{
var imageFile = args.Files[0] as StorageFile;
// Ensure the stream is disposed once the image is loaded
using (IRandomAccessStream fileStream = await imageFile.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
ImageControl.Source = bitmapImage;
await _viewModel.Upload(imageFile);
}
}
}
Create the file stream:
internal async Task Upload(Windows.Storage.StorageFile file)
{
var fileStream = await file.OpenAsync(FileAccessMode.Read);
fileStream.Seek(0);
var reader = new Windows.Storage.Streams.DataReader(fileStream.GetInputStreamAt(0));
await reader.LoadAsync((uint)fileStream.Size);
Globals.MemberId = ApplicationData.Current.LocalSettings.Values[Globals.PROFILE_KEY];
var userName = "Rico";
var sex = 1;
var url = string.Format("{0}{1}?memberid={2}&name={3}&sex={4}", Globals.URL_PREFIX, "api/Images", Globals.MemberId, userName,sex);
byte[] image = new byte[fileStream.Size];
await UploadImage(image, url);
}
Create a memory stream from the image:
public async Task UploadImage(byte[] image, string url)
{
Stream stream = new System.IO.MemoryStream(image);
HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream());
Uri resourceAddress = null;
Uri.TryCreate(url.Trim(), UriKind.Absolute, out resourceAddress);
Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, resourceAddress);
request.Content = streamContent;
var httpClient = new Windows.Web.Http.HttpClient();
var cts = new CancellationTokenSource();
Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token);
}

Save contact thumbnail on file

I would like save a profile picture in a file on localstorage.
With this code retrieval IRandomAccessStreamWithContentType but I don't understand how to save it on disk.
var contactPicker = new Windows.ApplicationModel.Contacts.ContactPicker();
contactPicker.CommitButtonText = "Select";
var contact = await contactPicker.PickSingleContactAsync();
using (IRandomAccessStreamWithContentType stream = await contact.GetThumbnailAsync())
{
//Save stream on LocalFolder
}
Assuming IRandomAccessStreamWithContentType works like any other stream, this should do the trick:
using (IRandomAccessStreamWithContentType stream = await contact.GetThumbnailAsync())
{
using(FileStream fs = new FileStream("path", FileMode.CreateNew))
{
stream.CopyTo(fs);
}
}

How to Stream an image to a client app in asp.net web api?

I have to retrieve an image from the disk or a web link , resize it and stream it to the client app. This is my controller method.
[HttpPost]
[ActionName("GetImage")]
public HttpResponseMessage RetrieveImage(ImageDetails details)
{
if (!details.Filename.StartsWith("http"))
{
if (!FileProvider.Exists(details.Filename))
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound, "File not found"));
}
var filePath = FileProvider.GetFilePath(details.Filename);
details.Filename = filePath;
}
var image = ImageResizer.RetrieveResizedImage(details);
MemoryStream stream = new MemoryStream();
// Save image to stream.
image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
var response = new HttpResponseMessage();
response.Content = new StreamContent(stream);
response.Content.Headers.ContentDisposition
= new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = details.Filename;
response.Content.Headers.ContentType
= new MediaTypeHeaderValue("application/octet-stream");
return response;
}
And this is how am sending the web link(in this case) and receiving the image at the client app end.
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:27066");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/octet-stream"));
ImageDetails img = new ImageDetails { Filename = "http://2.bp.blogspot.com/-W6kMpFQ5pKU/TiUwJJc8iSI/AAAAAAAAAJ8/c3sJ7hL8SOw/s1600/2011-audi-q7-review-3.jpg", Height = 300, Width = 200 };
var response = await client.PostAsJsonAsync("api/Media/GetImage", img);
response.EnsureSuccessStatusCode(); // Throw on error code.
var stream = await response.Content.ReadAsStreamAsync();
FileStream fileStream = System.IO.File.Create("ImageName");
// Initialize the bytes array with the stream length and then fill it with data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, (int)bytesInStream.Length);
// Use write method to write to the specified file
fileStream.Write(bytesInStream, 0, (int) bytesInStream.Length);
MessageBox.Show("Uploaded");
The image is being retrieved from the web link and the resizing is done properly but am not sure if its being streamed proeprly as its creating a 0kb file with "ImageName" when received at client app. Can anyone please tell me where am going wrong? I have been banging my head about it all day :(
Try resetting the position of the memory stream before passing it to the response:
stream.Position = 0;
response.Content = new StreamContent(stream);
I suppose that your image resizing library is leaving the position of the memory stream at the end.

Categories