我有这段代码从网络服务中检索图像并将其保存到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();
}
}
我想知道是否有办法将图片bytes[]
转换为缩略图版本(例如50x50),然后再将其写入StorageFile
。
答案 0 :(得分:1)
以下是调整图像流大小的代码:
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();
}
当你获得图像流时,你应该在将其保存为StorageFile之前进行调整大小。当然,您可以在将其保存到StorageFile后稍后执行此操作。