我想将图像文件从本地磁盘加载到writeablebitmap图像,因此我可以让用户对其进行编辑。当我创建一个WriteableBitmap对象时,构造函数需要pixelwidth和pixelheight参数,我不知道从哪里得到这两个,任何人都可以帮忙吗?
答案 0 :(得分:3)
尝试以下代码。有一种直接的方法(使用 BitmapImage 加载图像,然后将此对象直接传递给 WriteableBitmap 构造函数,但我不确定这是否按预期工作或它有性能问题,不记得了):
BitmapSource bmp = BitmapFrame.Create(
new Uri(@"C:\Users\Public\Pictures\Sample Pictures\Koala.jpg", UriKind.Relative),
BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
if (bmp.Format != PixelFormats.Bgra32)
bmp = new FormatConvertedBitmap(bmp, PixelFormats.Bgra32, null, 1);
// Just ignore the last parameter
WriteableBitmap wbmp = new WriteableBitmap(bmp.PixelWidth, bmp.PixelHeight,
kbmp.DpiX, bmp.DpiY, bmp.Format, bmp.Palette);
Int32Rect r = new Int32Rect(0, 0, bmp.PixelWidth, bmp.PixelHeight);
wbmp.Lock();
bmp.CopyPixels(r, wbmp.BackBuffer, wbmp.BackBufferStride * wbmp.PixelHeight,
wbmp.BackBufferStride);
wbmp.AddDirtyRect(r);
wbmp.Unlock();
答案 1 :(得分:3)
在定义WriteableBitmap图像时不要关心pixelWidth和pixelHeight,请试试这个:
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
WriteableBitmap image = new WriteableBitmap(1, 1);
image.SetSource(stream);
WriteableBitmapImage.Source = image;
}
答案 2 :(得分:3)
如果你想拥有正确的像素宽度和高度,你需要首先将它加载到BitmapImage中以正确填充它:
StorageFile storageFile =
await StorageFile.GetFileFromApplicationUriAsync("ms-appx:///myimage.png");
using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.Read))
{
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
WriteableBitmap writeableBitmap =
new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
fileStream.Seek(0);
await writeableBitmap.SetSourceAsync(fileStream);
}
(适用于WinRT应用)