0

WPF で CroppedBitmap メソッドを使用して画像をトリミングしています。必須の入力パラメーターは int32Rect です。しかし、私の画像の高さと幅の値は2倍(ピクセル)です。したがって、Double を Int に切り捨てずに、double 値 (ピクセル) を使用して画像をトリミングしたい

4

1 に答える 1

1

PixelWidthおよびPixelHeightプロパティを使用する必要があります。それらが表示されない場合 ( Intellisenseがそれらを見つけられない場合)、as演算子を使用してBitmapSourceにキャストできます。例えば:

BitmapSource src = yourImage as BitmapSource;
CroppedBitmap chunk = new CroppedBitmap(src, new Int32Rect(src.PixelWidth / 4, src.PixelHeight / 4, src.PixelWidth / 2, src.PixelHeight / 2));

ちなみに、変換が実行できなかった場合、 as演算子はnullを返します (そのため、 BitmapSourceから派生したものであることが確実でない限り、上記の例の変換後にないかどうかを確認することをお勧めしますsrc) 。 nullyourImage


編集 :

これが必要かどうかはわかりませんが、入力としてRect (浮動小数点値) を受け入れ、CroppedBitmapを返すメソッドを次に示します。

    public static CroppedBitmap GetCroppedBitmap(BitmapSource src, Rect r)
    {
        double factorX, factorY;

        factorX = src.PixelWidth / src.Width;
        factorY = src.PixelHeight / src.Height;
        return new CroppedBitmap(src, new Int32Rect((int)Math.Round(r.X * factorX), (int)Math.Round(r.Y * factorY), (int)Math.Round(r.Width * factorX), (int)Math.Round(r.Height * factorY)));
    }

例:

    BitmapImage bmp = new BitmapImage(new Uri(@"c:\Users\Public\Pictures\Sample Pictures\Koala.jpg", UriKind.Relative));
    CroppedBitmap chunk = GetCroppedBitmap(bmp, new Rect(bmp.Width / 4, bmp.Height / 4, bmp.Width / 2, bmp.Height / 2));
    JpegBitmapEncoder jpg = new JpegBitmapEncoder();
    jpg.Frames.Add(BitmapFrame.Create(chunk));
    FileStream fp = new FileStream("chunk.jpg", FileMode.Create, FileAccess.Write);
    jpg.Save(fp);
    fp.Close();
于 2013-01-08T19:37:19.693 に答える