1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C#のImageMagickでカラーモードがRGBの画像を保存しなおしたらグレーになった

Posted at

環境

Windows 10 Pro
Visual Studio 2017 Professional
Magick.NET-Q16-AnyCPU v7.14

事象再現

パッと見にはグレースケールの画像なんだけど、Photoshop等で確認するとRGBになっている画像がありました。
※本来の画像の一部をQiitaの記事用に切り抜いて使っています。元データには模様がついています。

before.png

この画像をC#のMagick.Netを使ってリサイズした画像がこちらです。

after.png

いや、グレースケールになっとるやないかい。

もちろんすべての画像で起こるわけではないです。
RGBそれぞれの値が全画素で一致している場合に勝手に変換してくれている印象です。
パッと見グレースケールでも、各ピクセルのどこか1つでもRGB値に差異があればRGB保持のままだと思います。

変換部分のコードは以下になります。

string outPath = @"C:\temp"; // 出力先フォルダ
string filepath = @"C:\temp\test.tiff"; // 入力画像
int toHeight = 50; // 拡大後の高さ

string filename = Path.GetFileNameWithoutExtension(filepath);
string ext = Path.GetExtension(path);

using (var img = new ImageMagick.MagickImage(path))
{
    int wid = img.Width;
    int hei = img.Height;

    double scale = ((double)toHeight / hei);
    double newWid = scale * wid;

    // フィルター指定
    img.FilterType = ImageMagick.FilterType.Lanczos;

    // リサイズ実行
    img.Resize((int)Math.Ceiling(newWid), toHeight);

    // 保存
    img.Write(Path.Combine(outPath, $"{filename}_out{ext}"));
}

解決方法

PreserveColorType();を使う

「Preserve=保持する」とかそういう意味だと思ったので、使ってみたらいけました。

SetAttribute("colorspace:auto-grayscale", "false");を使う

どこかで見た記事だと、PreserveColorType()の中でも同じことをやっているそうな。
colorspace:auto-grayscaleについては、ImageMagickのコマンドラインオプションにも説明が載っています。

ColorType = ImageMagick.ColorType.TrueColor;を使う(tiff画像の場合)

コマンドラインオプションの説明を読むと、以下のような記述があったので、試したらいけました。

PNG and TIF do not need this define. With PNG, just use PNG24:image. With TIF, just use -type truecolor.

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?