3

我有一种方法可以从面板中保存图像。此方法使用 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;
    }
4

1 回答 1

19

您需要使用 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();
    }
}

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

于 2012-09-28T18:56:17.643 回答