C#で画像を切り抜く方法を書きました。これは、新しいビットマップを作成し、元の画像から指定された長方形(トリミングされる領域)をその上に描画することによって行われます。
私が試した画像では、間違った結果が生成されていました。結果の画像のサイズは適切でしたが、内容はそれでした。画像を2倍に拡大してからトリミングしたようなものでした。最終的にこの行を追加すると修正されました:
result.setResolution(72, 72)
しかし、なぜ解決策が必要なのですか?私はピクセルを扱っているだけで、インチやセンチメートルは扱っていません。また、正しい解像度は何でしょうか?
完全なコードは次の拡張メソッドです。
public static Bitmap Crop(this Image image, int x, int y, int width, int height) {
Bitmap result = new Bitmap(width, height);
result.SetResolution(72, 72);
// Use a graphics object to draw the resized image into the bitmap.
using (Graphics graphics = Graphics.FromImage(result)) {
// High quality.
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
// Draw the image into the target bitmap.
graphics.DrawImage(image, 0, 0, new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
}
return result;
}