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

如何在C#中无需保存到本地文件系统即可在PictureBox中显示图像?

在C#中直接在PictureBox显示图像(无需保存到本地)

你可以通过将WIA的ImageFile直接转换为System.Drawing.Image对象,跳过本地文件保存步骤,直接赋值给PictureBox的Image属性来实现。

修改后的代码示例:

using System.IO;
using System.Drawing;
using WIA;

// 获取JPG格式的扫描图像
var imgFile = (ImageFile)ScanerItem.Transfer(FormatID.wiaFormatJPEG);

// 创建MemoryStream来存储图像数据
using (var memoryStream = new MemoryStream())
{
    var iStream = imgFile.FileData;
    byte[] buffer = new byte[4096];
    int bytesRead;
    IntPtr pBytesRead;

    // 将WIA的IStream内容读取到MemoryStream中
    while ((bytesRead = iStream.Read(buffer, buffer.Length, out pBytesRead)) > 0)
    {
        memoryStream.Write(buffer, 0, bytesRead);
    }
    // 重置流位置到起始处
    memoryStream.Position = 0;

    // 直接将图像加载到PictureBox
    pictureBox1.Image = Image.FromStream(memoryStream);
}

关键说明:

  • 核心思路是把WIA返回的ImageFile中的数据流提取到MemoryStream,再通过Image.FromStream转换为WinForms可用的Image对象
  • 如果需要后续对图像进行操作,建议克隆图像对象后再释放流,避免流被释放导致图像无法使用:
    pictureBox1.Image = Image.FromStream(memoryStream).Clone() as Image;
    
  • 窗体关闭时记得释放PictureBox的图像资源,防止内存泄漏:
    pictureBox1.Image?.Dispose();
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 12:36:32