【C#】取得并改变图像解析度

时间:2023-03-10 02:50:09
【C#】取得并改变图像解析度
using System;
using System.Drawing;
using System.IO; class Program
{
  static void Main()
  {
    // 画像を読み込む
    string basePath = @"C:\picture.png";
    Bitmap bmpOrg = Bitmap.FromFile(basePath) as Bitmap;     // 画像解像度を取得する
    float hRes = bmpOrg.HorizontalResolution;
    float vRes = bmpOrg.VerticalResolution;
    Console.WriteLine(
      "水平解像度:{0} dpi、垂直解像度:{1} dpi", hRes, vRes);     if (hRes != 96.0F || vRes != 96.0F)
    {
      // 画像解像度を変更して新しいBitmapオブジェクトを作成
      Bitmap bmpNew = new Bitmap(bmpOrg.Width, bmpOrg.Height);
      bmpNew.SetResolution(96.0F, 96.0F);       // 新しいBitmapオブジェクトに元の画像内容を描画
      Graphics g = Graphics.FromImage(bmpNew);
      g.DrawImage(bmpOrg, , , bmpOrg.Width, bmpOrg.Height);
      g.Dispose();       // 画像を保存
      string dirName = Path.GetDirectoryName(basePath);
      string fileName = Path.GetFileNameWithoutExtension(basePath);
      string extName = Path.GetExtension(basePath);
      string newPath = Path.Combine(
        dirName, fileName + "_new" + extName);
      bmpNew.Save(newPath);
      bmpNew.Dispose();
      Console.WriteLine("解像度を96dpiに変更しました。");
    }     // 画像リソースを解放
    bmpOrg.Dispose();     // メッセージを確認できるように実行を停止
    Console.ReadKey();
  }
}