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

如何使用Ghostscript将PDF转换为MemoryStream中的图像?

如何用GhostscriptWrapper将PDF转换为MemoryStream中的图像

要实现PDF转内存流图像、无需保存到本地文件,直接使用GhostscriptWrapper提供的Stream重载版本的GenerateOutput方法即可,不用指定本地文件路径。

修改后的代码示例:

// 初始化Ghostscript设置
GhostscriptSettings gs = new GhostscriptSettings();
gs.Device = GhostscriptDevices.png16m;
gs.Page = new GhostscriptPages { Start = page, End = page };
gs.Resolution = new Size { Height = 150, Width = 150 };
gs.Size = new GhostscriptPageSize { Native = GhostscriptPageSizes.a4 };

// 创建内存流用于接收图像数据
using (MemoryStream imageStream = new MemoryStream())
{
    // 调用接受Stream参数的GenerateOutput重载
    GhostscriptWrapper.GenerateOutput(@"C:\PDFViewer\my\test.pdf", imageStream, gs);
    
    // 转换完成后,重置流的位置到起始处,方便后续读取
    imageStream.Position = 0;
    
    // 这里可以直接用这个流加载图像,比如在WinForms中:
    // pictureBox.Image = Image.FromStream(imageStream);
    // 或者WPF中:
    // BitmapImage bitmap = new BitmapImage();
    // bitmap.BeginInit();
    // bitmap.StreamSource = imageStream;
    // bitmap.CacheOption = BitmapCacheOption.OnLoad;
    // bitmap.EndInit();
    // imageControl.Source = bitmap;
}

关键说明:

  • 替换原来的本地输出路径参数为MemoryStream实例,Ghostscript会直接把图像数据写入这个流
  • 必须在使用流前重置Position到0,否则读取会从流的末尾开始,读不到有效数据
  • 用using包裹MemoryStream可以自动释放资源,避免内存泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 04:47:37