Applicare il livello alpha ad un immagine

April 15, 2011

Per un applicazione per dispositivi iOS ho dovuto effettuare dei piccolissimi ritocchi a delle foto su dispositivo. In questo breev post descrivo il procedimento per la modifica di un'immagine applicando un livello di trasparenza detto livello alpha.

Ecco il codice del metodo da usare :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
-(CGImageRef) CopyImageAndAddAlphaChannel: (GImageRef)sourceImage {
CGImageRef retVal = NULL;
size_t width = CGImageGetWidth(sourceImage);
size_t height = CGImageGetHeight(sourceImage);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef offscreenContext = CGBitmapContextCreate(NULL, width, height,
8, 0, colorSpace, kCGImageAlphaPremultipliedFirst);
if (offscreenContext != NULL) {
CGContextDrawImage(offscreenContext, CGRectMake(0, 0, width, height), sourceImage);
retVal = CGBitmapContextCreateImage(offscreenContext);
CGContextRelease(offscreenContext);
}

CGColorSpaceRelease(colorSpace);
return retVal;
}

La funzione per la modifica dell’immagine diventa così :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
- (UIImage*)maskImage:(UIImage *)image withMask:(UIImage *)maskImage {
CGImageRef maskRef = maskImage.CGImage;
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef), NULL, false);
CGImageRef sourceImage = [image CGImage];
CGImageRef imageWithAlpha = sourceImage;
//add alpha channel for images that don’t have one (ie GIF, JPEG, etc…)
//this however has a computational cost
if ((CGImageGetAlphaInfo(sourceImage) == kCGImageAlphaNone) || (CGImageGetAlphaInfo(sourceImage) == kCGImageAlphaNoneSkipFirst))
{imageWithAlpha =[self CopyImageAndAddAlphaChannel:(CGImageRef)sourceImage];
}

CGImageRef masked = CGImageCreateWithMask(imageWithAlpha, mask);
CGImageRelease(mask);
//release imageWithAlpha if it was created by CopyImageAndAddAlphaChannel
if (sourceImage != imageWithAlpha) {
CGImageRelease(imageWithAlpha);
}
UIImage* retImage = [UIImage imageWithCGImage:masked];
CGImageRelease(masked);
return retImage;
}

Fonti :
1) http:/iphonedevelopertips.com/cocoa/how-to-mask-an-image.html
2) http://pastie.org/418627