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

Converting a System.Windows.Media.Drawing object to Bitmap bytes

我有一个 System.Windows.Media.Drawing 对象,我想将其转换为 Bitmap 对象,然后从那里提取表示图像的字节。我查看了互联网,似乎找不到如何做我需要的事情,所以任何帮助将不胜感激。

所以我终于找到了一种将 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;
}

是的,这很糟糕,但它确实有效。

你可以试试:

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

这项工作也适用于位图。