3

件名に記載されているように、私は画像を持っています:

    private Image testing;
    testing = new Bitmap(@"sampleimg.jpg");

それを 3 x 3 のマトリックスに分割して、合計で 9 つの画像を保存したいと思います。これを簡単に行うためのヒントやコツはありますか? 私はビジュアル スタジオ 2008 を使用しており、スマート デバイスで作業しています。いくつかの方法を試しましたが、取得できません。これは私が試したものです:

        int x = 0;
        int y = 0;
        int width = 3;
        int height = 3;


        int count = testing.Width / width;
        Bitmap bmp = new Bitmap(width, height);


        Graphics g = Graphics.FromImage(bmp);


        for (int i = 0; i < count; i++)
        {
            g.Clear(Color.Transparent);
            g.DrawImage(testing, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
            bmp.Save(Path.ChangeExtension(@"C\AndrewPictures\", String.Format(".{0}.bmp",i)));
            x += width;
        } 
4

1 に答える 1

9

.NET のバージョンに応じて、次のいずれかを実行してトリミングできます。

.NET 2.0

private static Image cropImage(Image img, Rectangle cropArea)
{
   Bitmap bmpImage = new Bitmap(img);
   Bitmap bmpCrop = bmpImage.Clone(cropArea,
   bmpImage.PixelFormat);
   return (Image)(bmpCrop);
}

または.NET 3.5+

// Create an Image element.
Image croppedImage = new Image();
croppedImage.Width = 200;
croppedImage.Margin = new Thickness(5);

// Create a CroppedBitmap based off of a xaml defined resource.
CroppedBitmap cb = new CroppedBitmap(     
   (BitmapSource)this.Resources["masterImage"],
   new Int32Rect(30, 20, 105, 50));       //select region rect
croppedImage.Source = cb;                 //set image source to cropped

ご覧のとおり、実行していることは少し単純です。最初の例では、現在のイメージのクローンを作成し、そのサブセットを取得します。2 番目の例ではCroppedBitmap、コンストラクターから直接イメージのセクションを取得することをサポートする を使用しています。

分割部分は単純な計算で、画像を 9 セットの座標に分割し、コンストラクターに渡すだけです。

于 2010-05-24T05:25:44.163 に答える