Ⅰ. はじめに
System.Drawing は WindowsのGDI+に依存している為、標準の.NET Coreで利用することができません。
解決策として System.Drawing.Common を使う方法を紹介します。
ただし、非推奨です。
Ⅱ. やり方
1. NuGetからインストールする
dotnet add package System.Drawing.Common
2. サンプルプログラムを書く
using System.Drawing; var file = File.OpenRead("input.png"); #pragma warning disable CA1416 var bmp = new Bitmap(file); bmp.Save("output.png"); #pragma warning restore
3. 実行結果
トラブルシューティング
Q. Linuxで実行すると以下のエラーが表示されます。
Unhandled Exception: System.TypeInitializationException: The type initializer for 'Gdip' threw an exception. ---> System.DllNotFoundException: Unable to load DLL 'libgdiplus': The specified module could not be found.
A. 以下手順を実行する必要があります
1. 以下のコマンドを実行してlibgdiplusをインストールする
apt install -y libgdiplus
2. プロジェクトルートにruntimeconfig.template.jsonを作成する
{ "configProperties": { "System.Drawing.EnableUnixSupport": true } }
3. csprojファイルを編集する
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> </PropertyGroup> </Project>
4. 発行する
dotnet publish -c Release