How to get a masked UIImage without bad resolution?

50 views Asked by At

I have an iOS application. I take a picture from my camera and I save this then crop this with a mask. The first image from the camera is saved correctly, but when I apply the mask it is saved with a low resolution and a stretched image.

I'm using this Objective-C code into my application to apply the mask.

- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)mask_Image {
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    //UIImage *maskImage = maskImage1;
    CGImageRef maskImageRef = [mask_Image CGImage];
    // create a bitmap graphics context the size of the image
    CGContextRef mainViewContentContext = CGBitmapContextCreate (NULL, mask_Image.size.width, mask_Image.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
    if (mainViewContentContext==NULL)
        return NULL;
    CGFloat widthratio = 0;
    CGFloat heightratio = 0;
    widthratio = mask_Image.size.width / image.size.width;
    heightratio = mask_Image.size.height / image.size.height;
    CGRect rect1 = {{0, 0}, {mask_Image.size.width, mask_Image.size.height}};
    CGRect rect2 = {{-((image.size.width*widthratio)-mask_Image.size.width)/2 , -((image.size.height*heightratio)-mask_Image.size.height)/2}, {image.size.width*widthratio, image.size.height*heightratio}};
    CGContextClipToMask(mainViewContentContext, rect1, maskImageRef);
    CGContextDrawImage(mainViewContentContext, rect2, image.CGImage);
    // Create CGImageRef of the main view bitmap content, and then
    // release that bitmap context
    CGImageRef newImage = CGBitmapContextCreateImage(mainViewContentContext);
    CGContextRelease(mainViewContentContext);
    UIImage *theImage = [UIImage imageWithCGImage:newImage];
    CGImageRelease(newImage);
    // return the image

    NSData* imageData =  UIImagePNGRepresentation(theImage);     // get png representation
    UIImage* pngImage = [UIImage imageWithData:imageData];
    UIImageWriteToSavedPhotosAlbum(pngImage, nil, nil, nil);
    return theImage;
}

I want get this correctly like:

  1. I take my picture from the camera:

enter image description here

  1. I apply my mask image to the camera image in the position that I wanted:

enter image description here

  1. And I get my cropped image masked:

enter image description here

How can I get the correct masked image?

0

There are 0 answers