c# – 在LocalFolder中存储BitmapImage – UWP
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 在LocalFolder中存储BitmapImage – UWP,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2516字,纯文字阅读大概需要4分钟。
内容图文
![c# – 在LocalFolder中存储BitmapImage – UWP](/upload/InfoBanner/zyjiaocheng/810/db6c20a119454866ad7896cd11ee77c2.jpg)
我正在尝试使用UWP上的C#将BitmapImage存储到文件系统.图像使用图形api从Facebook下载并作为BitmapImage返回.该部分工作,并检索图像(一旦我可以存储它,测试刚刚放在本地文件夹中的图片)我正在使用以下代码:
public static async Task<BitmapImage> GetProfilePicture(string userId){
BitmapImage profilePicture = new BitmapImage();
StorageFolder pictureFolder = await
ApplicationData.Current.LocalFolder.GetFolderAsync("ProfilePictures");
StorageFile pictureFile = await pictureFolder.GetFileAsync(userId + ".jpg");
IRandomAccessStream stream = await pictureFile.OpenAsync(FileAccessMode.Read);
profilePicture.SetSource(stream);
return profilePicture;
这也有效,所以我想要的只是做相反的事情.首选结果如下:
public static async void SaveBitmapToFile(BitmapImage image, userId){
StorageFolder pictureFolder = await
ApplicationData.Current.LocalFolder.CreateFolderAsync(
"ProfilePictures",CreationCollisionOption.OpenIfExists);
//save bitmap to pictureFolder with name userId.jpg
}
我一直在寻找解决方案,但我似乎无法找到任何UWP平台.如何将Bitmap保存到文件?如果更容易使用其他扩展名,则扩展名不必是.jpg.
解决方法:
如果使用WriteableBitmap会更容易.例如,第一种方法是:
public static async Task<WriteableBitmap> GetProfilePictureAsync(string userId)
{
StorageFolder pictureFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync("ProfilePictures");
StorageFile pictureFile = await pictureFolder.GetFileAsync(userId + ".jpg");
using (IRandomAccessStream stream = await pictureFile .OpenAsync(FileAccessMode.Read))
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
WriteableBitmap bmp = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
await bmp.SetSourceAsync(stream);
return bmp;
}
}
然后你可以这样做:
public static async Task SaveBitmapToFileAsync(WriteableBitmap image, userId)
{
StorageFolder pictureFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("ProfilePictures",CreationCollisionOption.OpenIfExists);
var file = await pictureFolder.CreateFileAsync(userId + ".jpg", CreationCollisionOption.ReplaceExisting);
using (var stream = await file.OpenStreamForWriteAsync())
{
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream.AsRandomAccessStream());
var pixelStream = image.PixelBuffer.AsStream();
byte[] pixels = new byte[bmp.PixelBuffer.Length];
await pixelStream.ReadAsync(pixels, 0, pixels.Length);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)image.PixelWidth, (uint)image.PixelHeight, 96, 96, pixels);
await encoder.FlushAsync();
}
}
内容总结
以上是互联网集市为您收集整理的c# – 在LocalFolder中存储BitmapImage – UWP全部内容,希望文章能够帮你解决c# – 在LocalFolder中存储BitmapImage – UWP所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。