Teddy13
Teddy13

Reputation: 3854

Convert UIImage to 8 bits

I wish to convert a UIImage to 8 bits. I have attempted to do this but I am not sure if I have done it right because I am getting a message later when I try to use the image proccessing library leptonica that states it is not 8 bits. Can anyone tell me if I am doing this correctly or the code on how to do it?

Thanks!

CODE

 CGImageRef myCGImage = image.CGImage;
 CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(myCGImage));
 const UInt8 *imageData = CFDataGetBytePtr(data);

Upvotes: 2

Views: 3147

Answers (1)

Quxflux
Quxflux

Reputation: 3303

Following code will work for images without alpha channel:

    CGImageRef c = [[UIImage imageNamed:@"100_3077"] CGImage];

    size_t bitsPerPixel = CGImageGetBitsPerPixel(c);
    size_t bitsPerComponent = CGImageGetBitsPerComponent(c);
    size_t width = CGImageGetWidth(c);
    size_t height = CGImageGetHeight(c);

    CGImageAlphaInfo a = CGImageGetAlphaInfo(c);

    NSAssert(bitsPerPixel == 32 && bitsPerComponent == 8 && a == kCGImageAlphaNoneSkipLast, @"unsupported image type supplied");

    CGContextRef targetImage = CGBitmapContextCreate(NULL, width, height, 8, 1 * CGImageGetWidth(c), CGColorSpaceCreateDeviceGray(), kCGImageAlphaNone);

    UInt32 *sourceData = (UInt32*)[((__bridge_transfer NSData*) CGDataProviderCopyData(CGImageGetDataProvider(c))) bytes];
    UInt32 *sourceDataPtr;

    UInt8 *targetData = CGBitmapContextGetData(targetImage);

    UInt8 r,g,b;
    uint offset;
    for (uint y = 0; y < height; y++)
    {
        for (uint x = 0; x < width; x++)
        {
            offset = y * width + x;

            if (offset+2 < width * height)
            {
                sourceDataPtr = &sourceData[y * width + x];

                r = sourceDataPtr[0+0];
                g = sourceDataPtr[0+1];
                b = sourceDataPtr[0+2];

                targetData[y * width + x] = (r+g+b) / 3;
            }
        }
    }

    CGImageRef newImageRef = CGBitmapContextCreateImage(targetImage);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];

    CGContextRelease(targetImage);
    CGImageRelease(newImageRef);

With this code I converted an rgb image to an grayscale image: Original image Grayscale image

Hope this helps

Upvotes: 6

Related Questions