views:

404

answers:

2

I'm trying to resize an image loaded from disk - a JPG or PNG (I don't know the format when I load it) - and then save it back to disk.

I've got the following code which I've tried to port from objective-c, however I've got stuck on the last parts. Original Objective-C.

This may not be the best way of achieving what I want to do - any solution is fine for me.

int width = 100;
int height = 100;

using (UIImage image = UIImage.FromFile(filePath))
{
    CGImage cgimage = image.CGImage;
    CGImageAlphaInfo alphaInfo = cgimage.AlphaInfo;

    if (alphaInfo == CGImageAlphaInfo.None)
        alphaInfo = CGImageAlphaInfo.NoneSkipLast;

    CGBitmapContext context = new CGBitmapContext(IntPtr.Zero,
        width,
        height,
        cgimage.BitsPerComponent,
        4 * width,
        cgimage.ColorSpace,
        alphaInfo);

    context.DrawImage(new RectangleF(0, 0, width, height), cgimage);

    /*
    Not sure how to convert this part:

    CGImageRef  ref = CGBitmapContextCreateImage(bitmap);
    UIImage*    result = [UIImage imageWithCGImage:ref];

    CGContextRelease(bitmap);   // ok if NULL
    CGImageRelease(ref);
    */
}
A: 

To get an UIImage from context all you need to do is:

UIImage* result = UIImage.FromImage(context.ToImage());

Crawen
+1  A: 

In the upcoming MonoTouch we will have a scale method, this is its implementation in UIImage.cs:

    public UIImage Scale (SizeF newSize)
    {
        UIGraphics.BeginImageContext (newSize);
        var context = UIGraphics.GetCurrentContext ();
        context.TranslateCTM (0, newSize.Height);
        context.ScaleCTM (1f, -1f);

        context.DrawImage (new RectangleF (0, 0, newSize.Width, newSize.Height), CGImage);

        var scaledImage = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();

        return scaledImage;         
    }

Adjusted to be reused outside of MonoTouch:

    public static UIImage Scale (UIImage source, SizeF newSize)
    {
        UIGraphics.BeginImageContext (newSize);
        var context = UIGraphics.GetCurrentContext ();
        context.TranslateCTM (0, newSize.Height);
        context.ScaleCTM (1f, -1f);

        context.DrawImage (new RectangleF (0, 0, newSize.Width, newSize.Height), source.CGImage);

        var scaledImage = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();

        return scaledImage;         
    }
miguel.de.icaza