James
James

Reputation: 2600

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. 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?

Upvotes: 2

Views: 7087

Answers (3)

someone else
someone else

Reputation: 321

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

Upvotes: 3

Allen4Tech
Allen4Tech

Reputation: 2184

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;
}

Upvotes: 3

RandomEngy
RandomEngy

Reputation: 15413

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)

Upvotes: 3

Related Questions