crop and get rest of the Image in Objective-C

251 views Asked by At

I want to crop the image, and want to get the other portion of the image. Like the image as per below

enter image description here

and enter image description here

Here I want to create a transparent area of the selected portion of the image and make a new image.

I have also tried to get all the pixel and set alpha to 0 of select portion, but it didn't work.

Does anyone have any other solutions?

Here is the code I have used:

CGSize size = [UIImage imageNamed:fileName].size;
CGImageRef inImage = [UIImage imageNamed:fileName].CGImage;
CFDataRef ref = CGDataProviderCopyData(CGImageGetDataProvider(inImage));
UInt8 * buf = (UInt8 *) CFDataGetBytePtr(ref);
int length = CFDataGetLength(ref);
float value2 =  (1 + value-0.5);
NSLog(@"length  = %d",length);
int row = 0,col = 0;
for(int i=0; i<length; i+=4)
{

    int r = i;
    int g = i+1;
    int b = i+2;
    int a = i+3;


    col++;
    if ((col % (int)size.width)==0 ) {
        row++;
        col=0;
    }


    int red = buf[r];
    int green = buf[g];
    int blue = buf[b];
    int alpha = buf[a]; 


    if (col > 25 && col < 75 && row > 25 && row < 75) {
        alpha = 0;
    }


    buf[r] = SAFECOLOR(red);
    buf[g] = SAFECOLOR(green);
    buf[b] = SAFECOLOR(blue);
    buf[a] = SAFECOLOR(alpha);


}
NSLog(@"CGImageGetAlphaInfo %d",CGImageGetAlphaInfo(inImage));
NSLog(@"CGImageGetColorSpace %@",CGImageGetColorSpace(inImage));

CGContextRef ctx = CGBitmapContextCreate(buf,
                                         CGImageGetWidth(inImage),
                                         CGImageGetHeight(inImage),
                                         CGImageGetBitsPerComponent(inImage),
                                         CGImageGetBytesPerRow(inImage),
                                         kCGColorSpaceGenericRGB,
                                         kCGImageAlphaPremultipliedLast);

CGImageRef img = CGBitmapContextCreateImage(ctx);

imgView.image = [UIImage imageWithCGImage:img];
1

There are 1 answers

0
hamstergene On

Try doing it by painting transparent rectangle in kCGBlendModeCopy (which replaces destination pixels completely rather than blending with them)

UIImage* dst = [UIImage imageNamed:fileName];
UIGraphicsBeginImageContext(dst.size);
[dst drawInRect:CGRectMake(0,0,dst.size.width,dst.size.height)];
[[UIBezierPath bezierPathWithRect:CGRectMake(25,25,50,50)] 
 fillWithBlendMode:kCGBlendModeCopy alpha:0];
UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

The problem with your solution is probably in that in a bitmap with premultiplied alpha the R,G,B components are expected to be multiplied by A component, and that means if you set A to zero you must set R,G,B to zero too (as any value multiplied by A=0 will be zero).