我可以从资源中的图片创建WriteableBitmap。
Uri imageUri1 = new Uri("ms-appx:///Assets/sample1.jpg");
WriteableBitmap writeableBmp = await new WriteableBitmap(1, 1).FromContent(imageUri1);但是,我不能从图片目录创建WriteableBitmap,(我使用的是WinRT XAML Toolkit)
//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);这是正确的吗?
发布于 2013-02-06 14:00:59
这是一个完全的设计,但它似乎确实有效...
// 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);发布于 2013-02-06 15:22:23
正如菲利普所指出的,将图像读取到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模式可写位图,并且我通过了。
发布于 2013-02-06 10:10:49
WriteableBitmapFromBitmapImageExtension.FromBitmapImage()通过使用用于加载BitmapImage和IIRC的原始Uri工作,它只适用于来自appx的BitmapImage。在你的例子中甚至没有Uri,因为从Pictures文件夹加载只能通过从stream加载来完成,所以你的选择从最快到最慢(我认为)是:
WriteableBitmap打开,这样您就不需要重新打开它或复制比特。WriteableBitmap打开,然后创建一个相同大小的新WriteableBitmap并复制像素缓冲区。如果您需要两个副本,请使用我认为选项2可能比选项3更快,因为您避免了对压缩图像进行两次解码。
https://stackoverflow.com/questions/14718855
复制相似问题