WPF equivalent to Bitmap.LockBits
I have the following working code in a Win Forms application:
Bitmap bitmap = new Bitmap(imageWidth, imageHeight, PixelFormat.Format32bppArgb);
Rectangle rect = new Rectangle(0, 0, imageWidth, imageHeight);
BitmapData bitmapData = bitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
Tao.DevIl.Il.ilConvertImage(Tao.DevIl.Il.IL_BGRA, Tao.DevIl.Il.IL_UNSIGNED_BYTE);
Tao.DevIl.Il.ilCopy开发者_运维技巧Pixels(0, 0, 0, imageWidth, imageHeight, 1, Tao.DevIl.Il.IL_BGRA, Tao.DevIl.Il.IL_UNSIGNED_BYTE, bitmapData.Scan0);
bitmap.UnlockBits(bitmapData);
I would like to convert this code to be compatible with WPF and displayable in the UI. This means I will probably have to convert the System.Drawing.Bitmap to a System.Windows.Media.Imaging.BitmapImage.
However, instead of converting between the two, I was wondering if there's a directer/faster way to do this? Like doing something like LockBits() on the BitmapImage.
The ilCopyPixels() takes a IntPtr as last baram. In the old code I'm getting this form BitmapData.Scan0.
Edit:
Thanks to Erno's answer I came up with the following:
WriteableBitmap bitmap = new WriteableBitmap(imageWidth, imageHeight, 96, 96, PixelFormats.Bgra32, null);
bitmap.Lock();
Tao.DevIl.Il.ilCopyPixels(0, 0, 0, imageWidth, imageHeight, 1, Tao.DevIl.Il.IL_BGRA, Tao.DevIl.Il.IL_UNSIGNED_BYTE, bitmap.BackBuffer);
bitmap.Unlock();
However, when I set the bitmap as the source of an image I don't see anything. I'm not getting any exceptions though.
Thanks!
Have a look at the WriteableBitmap it takes care of most of these details.
The current temp fix I have is to convert the Bitmap to a BitmapSource using the following code:
Bitmap bitmap = new Bitmap(imageWidth, imageHeight, PixelFormat.Format32bppArgb);
Rectangle rect = new Rectangle(0, 0, imageWidth, imageHeight);
BitmapData bitmapData = bitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
Tao.DevIl.Il.ilCopyPixels(0, 0, 0, imageWidth, imageHeight, 1, Tao.DevIl.Il.IL_BGRA, Tao.DevIl.Il.IL_UNSIGNED_BYTE, bitmapData.Scan0);
Tao.DevIl.Il.ilDeleteImages(1, ref imageId);
bitmap.UnlockBits(bitmapData);
using (MemoryStream str = new MemoryStream())
{
bitmap.Save(str, ImageFormat.Bmp);
str.Seek(0, SeekOrigin.Begin);
BitmapDecoder bdc = new BmpBitmapDecoder(str, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
// Retrieve the BitmapSource
image1.Source = bdc.Frames[0];
}
Obviously, I would rather create a BitmapSource directly without the extra overhead of creating a Bitmap first. Any suggestions are still welcome!
精彩评论