I have this piece of code that retrieves a image from a webservice and saves it to a StorageFile
StorageFolder folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(Constants.DataDirectory, CreationCollisionOption.OpenIfExists);
StorageFile imgFile;
using (var httpClient = new HttpClient { BaseAddress = Constants.baseAddress })
{
string token = App.Current.Resources["token"] as string;
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
using (var response2 = await httpClient.GetAsync("user/image?userId=" + id))
{
Stream imageStream = await response2.Content.ReadAsStreamAsync();
if (imageStream.Length != 0)
{
byte[] bytes = new byte[imageStream.Length];
imageStream.Read(bytes, 0, (int)imageStream.Length);
imgFile = await folder.CreateFileAsync(fname, CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync(imgFile, bytes); //i want the image bytes to be of a smaller version of the image at this point
}
return await response2.Content.ReadAsStringAsync();
}
}
I would like to know if there is a way to convert the image bytes[]
to a thumbnail version (50x50 for example) before writing them into the StorageFile
.
Here is the code to resize the image stream:
var decoder = await BitmapDecoder.CreateAsync(stream);
var pixels = await decoder.GetPixelDataAsync();
var file = await folder.CreateFileAsync($"{_oriFile.DisplayName}_{size}.png",CreationCollisionOption.GenerateUniqueName);
using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);
encoder.BitmapTransform.ScaledWidth = size;
encoder.BitmapTransform.ScaledHeight = size;
encoder.SetPixelData(
decoder.BitmapPixelFormat,
decoder.BitmapAlphaMode,
decoder.PixelWidth, decoder.PixelHeight,
decoder.DpiX, decoder.DpiY,
pixels.DetachPixelData());
encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
await encoder.FlushAsync();
}
When you get the image stream, you should do the resize thing before saving it as StorageFile. Of course you can do this later after saving it to StorageFile.