我可以从资产的照片创建WriteableBitmap的。
Uri imageUri1 = new Uri("ms-appx:///Assets/sample1.jpg");
WriteableBitmap writeableBmp = await new WriteableBitmap(1, 1).FromContent(imageUri1);
但是,我无法从图片目录创建WriteableBitmap的,(我用的WinRT XAML工具包 )
//open image
StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
StorageFile file = await picturesFolder.GetFileAsync("sample2.jpg");
var stream = await file.OpenReadAsync();
//create bitmap
BitmapImage bitmap2 = new BitmapImage();
bitmap2.SetSource();
bitmap2.SetSource(stream);
//create WriteableBitmap, but cannot
WriteableBitmap writeableBmp3 =
await WriteableBitmapFromBitmapImageExtension.FromBitmapImage(bitmap2);
它是否正确 ?
这是一个总的诡计,但它似乎工作...
// load a jpeg, be sure to have the Pictures Library capability in your manifest
var folder = KnownFolders.PicturesLibrary;
var file = await folder.GetFileAsync("test.jpg");
var data = await FileIO.ReadBufferAsync(file);
// create a stream from the file
var ms = new InMemoryRandomAccessStream();
var dw = new Windows.Storage.Streams.DataWriter(ms);
dw.WriteBuffer(data);
await dw.StoreAsync();
ms.Seek(0);
// find out how big the image is, don't need this if you already know
var bm = new BitmapImage();
await bm.SetSourceAsync(ms);
// create a writable bitmap of the right size
var wb = new WriteableBitmap(bm.PixelWidth, bm.PixelHeight);
ms.Seek(0);
// load the writable bitpamp from the stream
await wb.SetSourceAsync(ms);
这里的方式读取图像的WriteableBitmap的工作原理菲利普指出:
StorageFile imageFile = ...
WriteableBitmap writeableBitmap = null;
using (IRandomAccessStream imageStream = await imageFile.OpenReadAsync())
{
BitmapDecoder bitmapDecoder = await BitmapDecoder.CreateAsync(
imageStream);
BitmapTransform dummyTransform = new BitmapTransform();
PixelDataProvider pixelDataProvider =
await bitmapDecoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied, dummyTransform,
ExifOrientationMode.RespectExifOrientation,
ColorManagementMode.ColorManageToSRgb);
byte[] pixelData = pixelDataProvider.DetachPixelData();
writeableBitmap = new WriteableBitmap(
(int)bitmapDecoder.OrientedPixelWidth,
(int)bitmapDecoder.OrientedPixelHeight);
using (Stream pixelStream = writeableBitmap.PixelBuffer.AsStream())
{
await pixelStream.WriteAsync(pixelData, 0, pixelData.Length);
}
}
请注意,我使用的像素格式和Alpha模式下可写的位图使用,而我通过。
WriteableBitmapFromBitmapImageExtension.FromBitmapImage()
的工作原理是使用原始的URI用于加载BitmapImage
和IIRC它仅与工作BitmapImage
■从APPX。 在你的情况下竟然没有一个开放的,因为从图片文件夹加载只能通过从流加载完成,所以从最快的选项,以最慢的(我觉得)是:
- 打开图像
WriteableBitmap
从一开始走,这样就不需要四处重新打开或复制位。 - 如果你需要有两个副本-打开它
WriteableBitmap
,然后创建一个新的WriteableBitmap
尺寸相同,并复制像素缓冲区。 - 如果你需要有两个副本-跟踪用来打开第一个位图,然后创建一个新的路径
WriteableBitmap
从同一文件作为原始加载它。
我认为,选择2可能比选项3,因为你避免两次解码压缩图像更快。