0
1

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.

PNG画像の解像度を保持しておいて、設定し直したら予期せぬ値になっていた話

0
Last updated at Posted at 2019-11-28

環境

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

事象

  1. PNG画像を読み込んで、オリジナルの解像度を取得しておく
  2. 途中、色々な処理をする(別拡張子で保存したりとかもする)
  3. 最後に、手順1で取得したオリジナルの解像度をppiで設定する → あら不思議、おかしな値が入ってるじゃないの

結論

事象を読んで気づいた方もいらっしゃるかと思いますが、問題があったのはここ。

  1. PNG画像を読み込んで、オリジナルの解像度を取得しておく

ここを、以下のようにすればいい。

  1. PNG画像を読み込んで、単位をppiにしてからオリジナルの解像度を取得しておく

なぜこのようなことが?

私も今回調べて初めて知りましたが、PNGはピクセルの物理サイズは持っていますが、その単位がppiではないようです。
なので、物理的なピクセルサイズをinch(2.54)で割ってあげれば、一応ppiは出せます。が、端数は出る。

この辺りのことは、私もさらっとしか調べていませんが、興味のある方は「PNG pHYs」みたいなキーワードとかで調べてみてください。
(そして、この記事の内容が間違っていたら教えてください…)

再現コード(抜粋)

意図せぬ値が設定されていたコード

string inPath = ""; // 入力画像のパス
string outPath = ""; // 最終出力画像のパス

double densityX;
using(MagickImage img = new MagickImage(inPath))
{
    // オリジナルのdensityを取得
    densityX = img.Density.X;
}

/* 色々処理 */

string tempPath = ""; // 色々処理した結果の一時ファイルのパス

using(MagickImage img = new MagickImg(tempPath)
{
    // 解像度を設定
    img.Density = new Density(densityX, DensityUnit.PixelsPerInch);

    // 保存
    img.Write(outPath);
}

修正後

string inPath = ""; // 入力画像のパス
string outPath = ""; // 最終出力画像のパス

double densityX;
using(MagickImage img = new MagickImage(inPath))
{
    // 単位をPixelsPerInchに替えてからdensityを取得
    Density density = mImg.Density.ChangeUnits(DensityUnit.PixelsPerInch);
    densityX = density.X;
}

/* 色々処理 */

string tempPath = ""; // 色々処理した結果の一時ファイルのパス

using(MagickImage img = new MagickImg(tempPath)
{
    // 解像度を設定
    img.Density = new Density(densityX, DensityUnit.PixelsPerInch);

    // 保存
    img.Write(outPath);
}

0
1
1

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?