0

I have an UIImage with some alpha values and want to make a gray version of it. I've been using the below, and it works for nonalpha parts of the image, however as alpha is not supported/turned off the alpha parts turn out black... How would I successfully turn alpha support on?

(I modified this from code floating around stackoverflow, to support other scales (read retina))

-(UIImage*)grayscaledVersion2 {
    // Create image rectangle with current image width/height
    const CGRect RECT = CGRectMake(0, 0, self.size.width * self.scale, self.size.height * self.scale);

    // Grayscale color space
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();

    // Create bitmap content with current image size and grayscale colorspace
    CGContextRef context = CGBitmapContextCreate(nil, RECT.size.width, RECT.size.height, 8, 0, colorSpace, kCGImageAlphaNone);
    // kCGImageAlphaNone = no alpha, kCGImageAlphaPremultipliedFirst/kCGImageAlphaFirst/kCGImageAlphaLast = crash

    // Draw image into current context, with specified rectangle
    // using previously defined context (with grayscale colorspace)
    CGContextDrawImage(context, RECT, [self CGImage]);

    // Create bitmap image info from pixel data in current context
    CGImageRef imageRef = CGBitmapContextCreateImage(context);

    UIImage* imageGray = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];
    DLog(@"greyed %@ (%f, %f %f) into %@ (%f, %f %f)", self, self.scale, self.size.width, self.size.height, imageGray, imageGray.scale, imageGray.size.width, imageGray.size.height);

    // Release colorspace, context and bitmap information
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);
    CFRelease(imageRef);

    return imageGray;
}
Jonny
  • 15,955
  • 18
  • 111
  • 232
  • I found this post containing heaps of tries. http://stackoverflow.com/questions/1298867/convert-image-to-grayscale will report back if I found anything that support retina(different scales) AND alpha. – Jonny Jun 05 '13 at 03:41
  • 2
    Try this -> http://incurlybraces.com/convert-transparent-image-to-grayscale-in-ios/ – borrrden Jun 05 '13 at 04:07
  • For now I decided to edit the alpha part out of my images to work around the problem, but that page looks to the point and promising so +1. – Jonny Jun 05 '13 at 04:14
  • As per apple documentation GreyScale bitmap context is either alpha only (no rgb) or alpha is none. https://developer.apple.com/library/archive/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_context/dq_context.html#//apple_ref/doc/uid/TP30001066-CH203-BCIBHHBB – Marek H Jul 30 '23 at 07:04

0 Answers0