首页 > 解决方案 > 从缓冲区数组创建 jpeg 图像

问题描述

我正在尝试从 RGBA 的缓冲区数组中保存 jpeg 图像。
我试过这段代码

byte[] buffer = new byte[m_FrameProps.ImgSize];
Marshal.Copy(m_BM.BackBuffer, buffer, 0, m_FrameProps.ImgSize); //m_BM is WriteableBitmap
using (MemoryStream imgStream = new MemoryStream(buffer))
{
    using (System.Drawing.Image image = System.Drawing.Image.FromStream(imgStream))
    {
        image.Save(m_WorkingDir + "1", ImageFormat.Jpeg); 
    }
} 

但我收到运行时错误:“System.Drawing.dll 中发生了“System.ArgumentException”类型的未处理异常

附加信息:参数无效。”

我也尝试创建位图,然后使用 JpegBitmapEncoder

Bitmap bitmap;
using (var ms = new MemoryStream(buffer))
{
    bitmap = new Bitmap(ms);
} 

但我得到了同样的错误。
我想这是因为阿尔法。
我该怎么做?我是否需要循环值并在没有 alpha 的情况下进行复制?

标签: c#jpeg

解决方案


仅从像素数据数组中构建图像是不可能的。至少还需要像素格式信息和图像尺寸。这意味着任何使用流直接从 ARGB 数组创建位图的尝试都将失败,Image.FromStream()Bitmap()方法都要求流包含某种标题信息来构造图像。

也就是说,假设您似乎知道要保存的图像的尺寸和像素格式,您可以使用以下方法:

public void SaveAsJpeg(int width, int height, byte[] argbData, int sourceStride, string path)
{
    using (Bitmap img = new Bitmap(width, height, PixelFormat.Format32bppPArgb))
    {
        BitmapData data = img.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, img.PixelFormat);
        for (int y = 0; y < height; y++)
        {
            Marshal.Copy(argbData, sourceStride * y, data.Scan0 + data.Stride * y, width * 4);
        }
        img.UnlockBits(data);
        img.Save(path, ImageFormat.Jpeg);
    }
}

推荐阅读