wpf C#-位图到字节数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12645705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 05:36:02  来源:igfitidea点击:

C#-Bitmap to Byte array

c#asp.netwpfwinforms

提问by user1399377

I have a method which saves the image from a panel. This method is using Bitmap class. I wants that my method should return byte array of the image.

我有一种方法可以从面板中保存图像。此方法使用 Bitmap 类。我希望我的方法应该返回图像的字节数组。

 private byte[] SaveImage()
    {
        byte[] byteContent = null;
        using (Bitmap bitmap = new Bitmap(500, 500))
        {
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                Rectangle rectangle = myPanel.Bounds;
                Point sourcePoints = myPanel.PointToScreen(new Point(myPanel.ClientRectangle.X, myPanel.ClientRectangle.Y));
                g.CopyFromScreen(sourcePoints, Point.Empty, rectangle.Size);
            }

            string fileName = @"E:\MyImages.Jpg";
            bitmap.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        return byteContent;
    }

回答by Joachim Isaksson

You'll need to use a MemoryStream to serialize the bitmap to an image format and get the bytes;

您需要使用 MemoryStream 将位图序列化为图像格式并获取字节;

using (Bitmap bitmap = new Bitmap(500, 500))
{
    using (Graphics g = Graphics.FromImage(bitmap))
    {
        ...
    }

    using (var memoryStream = new MemoryStream())
    {
        bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        return memoryStream.ToArray();
    }
}

There are multiple output formats to choose from, you may instead want Bmp or MemoryBmp.

多种输出格式可供选择,您可能需要 Bmp 或 MemoryBmp