【问题标题】:C#-Bitmap to Byte arrayC#-位图到字节数组
【发布时间】:2012-09-20 16:11:43
【问题描述】:

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

【问题讨论】:

  • 为什么返回 Null byteContent?您在代码中的哪个位置使用或分配 byteContent..?
  • 将位图保存到内存流并设置 byteContent = stream.ToArray();
  • @DJ KRAZE 实际上,我故意将 null 返回到字节数组变量,因为我不知道如何为它分配字节数组
  • 你为什么指出“wpf”作为标签? wpf 中的位图处理完全不同!

标签: c# asp.net wpf winforms


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-28
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    相关资源
    最近更新 更多