Laskar78
Laskar78

Reputation: 41

What is the equivalent function for WPF?

I have the following function that works in Windows Form but I will need help to make it work in WPF with the image control.

public static Bitmap CreateBitmap(byte[] bytes, int width, int height)
{
        var rgbBytes = new byte[bytes.Length * 3];
        for (var i = 0; i <= bytes.Length - 1; i++)
        {
            rgbBytes[(i * 3)] = bytes[i];
            rgbBytes[(i * 3) + 1] = bytes[i];
            rgbBytes[(i * 3) + 2] = bytes[i];
        }
        var bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);

        var data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);

        for (var i = 0; i <= bmp.Height - 1; i++)
        {
            var p = new IntPtr(data.Scan0.ToInt32() + data.Stride * i);
            System.Runtime.InteropServices.Marshal.Copy(rgbBytes, i * bmp.Width * 3, p, bmp.Width * 3);
        }

        bmp.UnlockBits(data);

        return bmp;
    }

Any help will be appreciated. Thanks

Upvotes: 1

Views: 208

Answers (1)

qqbenq
qqbenq

Reputation: 10460

Try something like this:

BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
      bmp.GetHbitmap(),
      IntPtr.Zero,
      System.Windows.Int32Rect.Empty,
      BitmapSizeOptions.FromWidthAndHeight(bmp.Width, bmp.Height));
image.Source = bs;

image is an Image control.

Also, please check this question as it mentions some important facts about bmp.GetHbitmap() leaking a handle.

Finally, this article might be of help.

Upvotes: 1

Related Questions