2

我想从本地磁盘加载一个图像文件到一个可写位图图像,这样我就可以让用户编辑它。当我创建一个WriteableBitmap对象时,构造函数需要pixelwidth和pixelheight参数,我不知道从哪里得到这两个,谁能帮忙?

4

3 回答 3

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();
于 2013-01-16T08:09:33.730 回答
3

定义 WriteableBitmap 图像时不要关心 pixelWidth 和 pixelHeight,请尝试以下操作:

using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
    WriteableBitmap image = new WriteableBitmap(1, 1);
    image.SetSource(stream);
    WriteableBitmapImage.Source = image;
}
于 2013-01-16T15:56:27.103 回答
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 应用程序)

于 2014-12-03T00:09:14.360 回答