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?
Asked
Active
Viewed 7,055 times
2
-
How do you load the image from file? – someone else Jan 16 '13 at 07:16
-
But I guess you load the image through a **BitmapImage** or something like that and **then** you create a **WriteableBitmap**, right? – someone else Jan 16 '13 at 07:32
-
Yes, I want to load the file and then convert it to writeablebitmap. But I don't know how. – James Jan 16 '13 at 07:35
3 Answers
3
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();

Vivek Jain
- 3,811
- 6
- 30
- 47

someone else
- 321
- 1
- 3
3
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;
}

Vivek Jain
- 3,811
- 6
- 30
- 47

Allen4Tech
- 2,094
- 3
- 26
- 66
3
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)

RandomEngy
- 14,931
- 5
- 70
- 113