在Objective-C中裁剪并获取其余图像

时间:2012-05-29 12:08:54

标签: objective-c crop image-editing

我想裁剪图像,并希望获得图像的其他部分。像下面的图像一样

enter image description here

enter image description here

在这里,我想创建图像所选部分的透明区域并制作新图像。

我还尝试获取所有像素并将alpha设置为选择部分的0,但它不起作用。

有没有人有其他解决方案?

以下是我使用的代码:

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 个答案:

答案 0 :(得分:0)

尝试在kCGBlendModeCopy中绘制透明矩形(完全替换目标像素而不是与它们混合)来做到这一点

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();

您的解决方案的问题可能在于,在预乘alpha 的位图中,R,G,B组件应该乘以A组件,这意味着如果将A设置为零你必须将R,G,B也设置为零(因为任何值乘以A = 0将为零)。