如何从 BitmapImage 创建 WriteableBitmap? [英] How to create WriteableBitmap from BitmapImage?

查看:28
本文介绍了如何从 BitmapImage 创建 WriteableBitmap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以从 Assets 中的图片创建 WriteableBitmap.

I could create WriteableBitmap from pictures in Assets.

Uri imageUri1 = new Uri("ms-appx:///Assets/sample1.jpg");
WriteableBitmap writeableBmp = await new WriteableBitmap(1, 1).FromContent(imageUri1);

但是,我无法从图片目录创建 WriteableBitmap,(我使用的是 WinRT XAML Toolkit)

but, I can't create WriteableBitmap from Pictures Directory,(I'm using 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);

这是正确的吗?

推荐答案

这完全是一个发明,但它似乎确实有效......

This is a total contrivance, but it does seem to work ...

// 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);

这篇关于如何从 BitmapImage 创建 WriteableBitmap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆