Jimmy
Jimmy

Reputation: 13

Extract sub image BitmapImage

I'm working on a C# Universal Project(Windows Desktop+Windows Phone) that requires me to display a lot of images. I'm trying to make use of the 'compressed' image I have been given.

This is the image: http://gyazo.com/b592a5fb6b4754c0aecc0223be56a3cf

The image consists out of sub-images that are all put into 1 image to save space. In the past I have programmed C# Desktop apps and used the following code to extract an image from the image that contains the sub images.

public Bitmap Load(int x, int y, int w, int h, string sprite)
{
    Bitmap original = new Bitmap(@"Images\" + sprite);
    Rectangle rectangle = new Rectangle(x, y, w, h);
    return (Bitmap)original.Clone(rectangle, original.PixelFormat);
}

Now that I am working on a Universal application (Desktop+Phone) the above code is no longer valid. I am forced to work with BitmapImages instead of Bitmap.

I have tried to convert it:

public BitmapImage Load(double x, double y, double w, double h, string sprite)
{
    BitmapImage original = new BitmapImage();
    original.UriSource = new Uri(@"Images\" + sprite);
    Rectangle rectangle = new Rectangle();
    rectangle.Width = w;
    rectangle.Height = h;
    rectangle.RadiusX = x;
    rectangle.RadiusY = y;
    return (BitmapImage)original.clone(rectangle, original.PixelFormat);
}

But the .clone and .PixelFormat functions are not present with BitmapImages. Any help in converting this code to work in C# Universal App would be much appreciated!

Upvotes: 1

Views: 2694

Answers (1)

Rob Caplan - MSFT
Rob Caplan - MSFT

Reputation: 21899

You can't extract the pixels from a BitmapImage. You'll need to either use a WriteableBitmap or BitmapDecoder to get access to the actual pixels.

With a BitmapDecoder you can read in specific segments of the image by calling GetPixelDataAsync with a BitmapTransform with just the Bounds you want to crop out of the bitmap.

With either a WriteableBitmap or a BitmapEncoder you can read in the full bitmap and then extract the sub-images after the fact. There isn't anything built in to copy sub-images out, but the math to find and copy a rectangle isn't hard and there are third party extensions (such as WriteableBitmapEx's Crop extension method) which can do it for you.

Upvotes: 3

Related Questions