将System.Windows.Media.Drawing对象转换为Bitmap字节

时间:2017-05-18 09:20:02

标签: c# bitmap system.windows.media

我有一个System.Windows.Media.Drawing对象,我想将其转换为Bitmap对象,然后从那里提取代表图像的字节。我看过互联网,似乎无法找到我需要的东西,所以任何帮助都会受到赞赏。

2 个答案:

答案 0 :(得分:0)

所以我终于找到了将System.Windows.Media.Drawing对象转换为System.Drawing.Bitmap对象的方法,然后从中获取表示图像数据的byte[]对象。以下情况并不漂亮,但确实有效。

public static byte[] DrawingToBytes(Drawing drawing)
{
    DrawingVisual visual = new DrawingVisual();
    using (DrawingContext context = visual.RenderOpen())
    {
        // If using the BitmapEncoder uncomment the following line to get a white background.
        // context.DrawRectangle(Brushes.White, null, drawing.bounds);
        context.DrawDrawing(drawing);
    }

    int width = (int)(drawing.Bounds.Width)
    int height = (int)(drawing.Bounds.Height)
    Bitmap bmp = new Bitmap(width, height);
    Bitmap bmpOut;

    using (Graphics g = Graphics.FromImage(bmp))
    {
        g.Clear(System.Drawing.Color.White);
        RenderTargetBitmap rtBmp = new RenderTargetBitmap(width, height, 
                                           bmp.HorizontalResolution,
                                           bmp.VerticalResolution,
                                           PixelFormats.Pbgra32);
        rtBmp.Render(visual);

        // Alternative using BmpBitmapEncoder, use in place of what comes after if you wish.
        // MemoryStream stream = new MemoryStream();
        // BitmapEncoder encoder = new BmpBitmapEncoder();
        // encoder.Frames.Add(BitmapFrame.Create(rtBmp));
        // encoder.save(stream);

        int stride = width * ((rtBmp.Format.BitsPerPixel + 7) / 8);
        byte[] bits = new byte[height * stride];
        bitmapSource.CopyPixels(bits, stride, 0);

        unsafe
        {
            fixed (byte* pBits = bits)
            {
                IntPtr ptr = new IntPtr(pBits);
                bmpOut = new Bitmap(width, height, stride,
                                    System.Drawing.Imaging.PixelFormat.Format32bppPArgb, ptr);
             }
        }

        g.DrawImage(bmpOut, 0, 0, bmp.Width, bmp.Height);
    }

    byte[] bytes;
    using (MemoryStream ms = new MemoryStream())
    {
        bmp.Save(ms, ImageFormat.bmp);
        data = ms.ToArray();
    }

    return bytes;
}

所以是的,它太可怕但实际上却有效。

答案 1 :(得分:0)

您可以尝试:

byte[] ImageToByte(Image image)
    {
        ImageConverter converter = new ImageConverter();
        return (byte[])converter.ConvertTo(img, typeof(byte[]));
    }

此功能也适用于位图。