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文件中添加以下配置之一:- 指定Windows运行时标识符(锁定为Windows平台):
<PropertyGroup> <RuntimeIdentifier>win-x64</RuntimeIdentifier> <!-- 32位系统用win-x86 --> </PropertyGroup> - 启用Windows Forms兼容(保留跨平台能力但启用Windows图形API支持):
<PropertyGroup> <UseWindowsForms>true</UseWindowsForms> </PropertyGroup>
- 指定Windows运行时标识符(锁定为Windows平台):
- 确认安装正确的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
相关产品推荐
相关产品推荐

