2
votes

I want to load an image file from local disk to a writeablebitmap image, so I can let users to edit it. 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?

3
How do you load the image from file? - someone else
But I guess you load the image through a BitmapImage or something like that and then you create a WriteableBitmap, right? - someone else
Yes, I want to load the file and then convert it to writeablebitmap. But I don't know how. - James

3 Answers

3
votes

If you want to have the correct pixel width and height, you need to load it into a BitmapImage first to populate it correctly:

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)

3
votes

Don't care the pixelWidth and pixelHeight when define the WriteableBitmap image, please try this:

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

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):

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