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

Windows+VS2019下.NET Core3.1调用Image.FromFile遇平台不支持错误

问题

在基于.NET Core 3.1的WorkerService中调用类库项目的函数(Windows 10系统下使用Visual Studio 2019本地编译),使用PdfSharp执行Image MyImage = Image.FromFile(imageLocation);代码行时,抛出错误:System.Drawing.Common is not supported on this platform。

涉事代码片段:

PdfDocument doc = new PdfDocument();
doc.Options.FlateEncodeMode = PdfFlateEncodeMode.BestCompression;
doc.Options.UseFlateDecoderForJpegImages = PdfUseFlateDecoderForJpegImages.Automatic;
doc.Options.NoCompression = false;
doc.Options.CompressContentStreams = true;
Image MyImage = Image.FromFile(imageLocation);
for (int PageIndex = 0; PageIndex < MyImage.GetFrameCount(FrameDimension.Page); PageIndex++)
{
    MyImage.SelectActiveFrame(FrameDimension.Page, PageIndex);
    XImage img = XImage.FromGdiPlusImage(MyImage);
    var page = new PdfPage();
    page.Size = PageSize.Letter;
    if (MyImage.Width > MyImage.Height)
    {
        // 处理横向扫描的图像,旋转90度
        MyImage.RotateFlip(RotateFlipType.Rotate90FlipNone);
        page.Rotate = 270;
    }
    doc.Pages.Add(page);
    XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[doc.Pages.Count - 1]);
    xgr.DrawImage(img, 0, 0, page.Width, page.Height);
    xgr.Dispose();
}
doc.Save(Savepath);
doc.Close();

解决方案

  • 配置项目Windows兼容性:.NET Core 3.1中System.Drawing.Common默认仅支持Windows,但如果项目未指定Windows运行时标识符,会触发平台不支持错误。在项目的.csproj文件中添加以下配置之一:
    1. 指定Windows运行时标识符(锁定为Windows平台):
      <PropertyGroup>
        <RuntimeIdentifier>win-x64</RuntimeIdentifier> <!-- 32位系统用win-x86 -->
      </PropertyGroup>
      
    2. 启用Windows Forms兼容(保留跨平台能力但启用Windows图形API支持):
      <PropertyGroup>
        <UseWindowsForms>true</UseWindowsForms>
      </PropertyGroup>
      
  • 确认安装正确的NuGet包:确保项目已安装System.Drawing.Common包,版本需与.NET Core 3.1兼容,可通过NuGet包管理器或命令行安装:
    Install-Package System.Drawing.Common -Version 4.7.0
    
  • 替换图像加载方式(规避GDI+依赖):如果不想依赖System.Drawing.Common,可直接使用PdfSharp的XImage.FromFile加载图像,替代原有的GDI+Image.FromFile方式(注意:此方法无法处理多页图像,如TIFF,这类场景仍需依赖GDI+或其他多页图像库):
    // 替换原代码中Image MyImage = Image.FromFile(imageLocation);及后续相关GDI+操作
    XImage img = XImage.FromFile(imageLocation);
    // 单页图像直接处理逻辑
    var page = new PdfPage();
    page.Size = PageSize.Letter;
    if (img.PixelWidth > img.PixelHeight)
    {
        page.Rotate = 270;
    }
    doc.Pages.Add(page);
    XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[doc.Pages.Count - 1]);
    xgr.DrawImage(img, 0, 0, page.Width, page.Height);
    xgr.Dispose();
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 02:40:33