Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

crop image without copying

I'm writing an application that requires me to split a large image into small tiles, 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 create basically a "reference" to the original image, and would just display as a sub rectangle of the image. However, the slow speed at which my split operation performs has lead me to believe that this is actually copying the source rect of the original image, which is very slow for large images (There is a noticeable 3-4 second pause when splitting a decent size image).

I looked around a bit but haven't been able to find a way to draw a bitmap as a sub rect of a large image, without copying any data. Any suggestions?

like image 908
phosphoer Avatar asked Oct 05 '22 14:10

phosphoer


1 Answers

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;
like image 117
intrepidis Avatar answered Oct 23 '22 06:10

intrepidis