简体   繁体   English

如何在windows8中从图像文件创建writeablebitmap图像

[英]How to create a writeablebitmap image from an image file in windows8

I want to load an image file from local disk to a writeablebitmap image, so I can let users to edit it. 我想将图像文件从本地磁盘加载到writeablebitmap图像,所以我可以让用户编辑它。 when I create a WriteableBitmap object, the constructor need pixelwidth and pixelheight parameters, I don't know where to get these two, anyone can help? 当我创建一个WriteableBitmap对象时,构造函数需要pixelwidth和pixelheight参数,我不知道从哪里得到这两个,有谁可以帮忙?

Try the following code. 请尝试以下代码。 There is an straightforward way to do this (load the image using BitmapImage and then pass this object directly to WriteableBitmap constructor, but I'm not sure if this works as expected or it has performance problem, don't remember): 有一种简单的方法可以做到这一点(使用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();

Don't care the pixelWidth and pixelHeight when define the WriteableBitmap image, please try this: 定义WriteableBitmap图像时不要关心pixelWidth和pixelHeight,请尝试这样做:

using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
    WriteableBitmap image = new WriteableBitmap(1, 1);
    image.SetSource(stream);
    WriteableBitmapImage.Source = image;
}

If you want to have the correct pixel width and height, you need to load it into a BitmapImage first to populate it correctly: 如果要获得正确的像素宽度和高度,则需要先将其加载到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);
}

(For WinRT apps) (适用于WinRT应用)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM