You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将像素数据字节数组转换为图像?附图像转字节数组代码

将字节数组还原为Bitmap图像的实现方法

很高兴看到你已经搞定了从Bitmap提取像素字节数组的部分!接下来咱们直接上对应的还原逻辑,核心是要和你导出时的参数(宽、高、像素格式、Stride)完全匹配,不然容易出现图像变形、颜色错乱的问题。

完整实现代码

// 定义字节数组转Bitmap的工具方法
void ByteArrayToBitmap(byte[] pixelBytes, int width, int height, PixelFormat pixelFormat)
{
    // 创建与原图像参数完全一致的空白Bitmap
    Bitmap restoredImg = new Bitmap(width, height, pixelFormat);
    
    // 锁定Bitmap的内存区域,准备写入像素数据
    BitmapData bitmapData = restoredImg.LockBits(
        new Rectangle(0, 0, width, height),
        ImageLockMode.WriteOnly, // 仅写入模式,比读写模式更高效
        pixelFormat);
    
    // 计算需要写入的总字节数(和导出逻辑一致:Stride * 图像高度)
    int totalBytes = bitmapData.Stride * bitmapData.Height;
    
    // 将字节数组复制到Bitmap的内存缓冲区
    Marshal.Copy(pixelBytes, 0, bitmapData.Scan0, totalBytes);
    
    // 解锁内存,完成数据写入
    restoredImg.UnlockBits(bitmapData);
    
    // 示例操作:将还原后的图像显示到PictureBox
    pictureBox1.Image = restoredImg;
    // 也可以直接保存为文件
    // restoredImg.Save(@"restored_24x30.bmp");
}

// 调用示例(对应你之前的导出场景)
void Button3Click(object sender, EventArgs e)
{
    // 假设你已经持有从Bitmap导出的byte[] bytes
    // 必须传入和原图像一致的宽、高、像素格式
    ByteArrayToBitmap(bytes, 24, 30, PixelFormat.Format24bppRgb);
}

关键注意事项

  • 参数严格匹配:width、height、PixelFormat必须和你导出字节数组时的原图像完全一致,否则会出现拉伸、颜色失真等问题。
  • Stride的意义:bitmapData.Stride是系统按4字节对齐后的每行像素实际字节数,不能直接用宽度×单像素字节数计算总长度,必须沿用Stride×高度的逻辑,和导出时保持统一。
  • 内存释放:一定要调用UnlockBits解锁内存,否则会导致Bitmap资源泄漏或无法正常使用。

内容的提问来源于stack exchange,提问作者Jackuze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:53:01