0

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;
}
4

2 に答える 2

1

DrawImageの誤ったオーバーロードを使用しています。SrcおよびDestrectsを指定するものを使用する必要があります。

graphics.DrawImage(image, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);

それを試してみて、うまくいかない場合はコメントで知らせてください。

于 2009-07-30T13:53:23.473 に答える
-1

答えは、ライブラリが実際に変更を加える方法にあると思います。メモリのいくつかのブロックをコピーして貼り付けるだけです。解像度は、ピクセルごとに使用されるビット/バイト数を指定します。コピーする必要のあるバイト数を知るには、ピクセルあたりのビット数/バイト数を知る必要があります。

したがって、これは単純な乗算とそれに続くメモリコピーだと思います。

よろしく

于 2009-07-30T06:59:00.437 に答える