c# - 从缓冲区数组创建 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 的情况下进行复制?
解决方案
仅从像素数据数组中构建图像是不可能的。至少还需要像素格式信息和图像尺寸。这意味着任何使用流直接从 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);
}
}
推荐阅读
- python-3.x - Kivy ScreenManager 与 Matlibplot 绘制实时数据
- visual-studio-code - 如何在 Visual Studio Code 的 Rust 项目中查看外部库的源代码?
- python - MongoEngine 递归嵌入
- android - 尝试使用 p4a 编译“Hello World”Kivy 项目
- django - 如何在 django 中展望并订购查询集?
- json - IdentityServer 4:我必须加密对 api 的 json 调用吗?
- java - 生成长固定大小的随机字符串
- javascript - 有没有办法制造某些组件(即s) 在网页上自动滚动?
- python - 如何使用css从单个href中的多个url中选择单个url?
- .htaccess - .htaccess 带有查询参数的永久重定向