Crop image without copying

I am writing an application that requires me to split a large image into small fragments, where each tile is essentially a cropped version of the original image.

Currently, my split operation looks something like this:

tile.Image = new BitmapImage();
tile.Image.BeginInit();
tile.Image.UriSource = OriginalImage.UriSource;
tile.Image.SourceRect = new Int32Rect(x * tileWidth + x, y * tileHeight, tileWidth, tileHeight);
tile.Image.EndInit();

Intuitively, I thought that this would basically create a β€œlink” to the original image and would just display as a sub-rectangle of the image. However, the slow speed at which my splitting operation is performed led me to think that it actually copies the original rectangle of the original image, which is very slow for large images (there is a noticeable pause of 3-4 seconds when splitting a decent image size )

I looked around a bit, but could not find a way to draw a bitmap as a sub-rectangle of a large image without copying any data. Any suggestions?

+5
source share
1 answer

Use the System.Windows.Media.Imaging.CroppedBitmap class:

// Create a CroppedBitmap from the original image.
Int32Rect rect = new Int32Rect(x * tileWidth + x, y * tileHeight, tileWidth, tileHeight);
CroppedBitmap croppedBitmap = new CroppedBitmap(originalImage, rect);

// Create an Image element.
Image tileImage = new Image();
tileImage.Width = tileWidth;
tileImage.Height = tileHeight;
tileImage.Source = croppedBitmap;
+4
source

All Articles