1

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

4

2 回答 2

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;
}

所以,是的,这很可怕,但它确实有效。

于 2017-06-07T14:23:33.413 回答
0

你可以试试:

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

这项工作也适用于位图。

于 2019-04-27T01:07:40.817 回答