将UIImage转换为8位

Ted*_*y13 2 objective-c ios

我希望将UIImage转换为8位.我试图这样做,但我不确定我是否做得对,因为我稍后在尝试使用图像处理库leptonica时收到一条消息,表明它不是8位.任何人都可以告诉我,如果我正确这样做或代码如何做到这一点?

谢谢!

 CGImageRef myCGImage = image.CGImage;
 CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(myCGImage));
 const UInt8 *imageData = CFDataGetBytePtr(data);
Run Code Online (Sandbox Code Playgroud)

Luk*_*kas 6

以下代码适用于没有Alpha通道的图像:

    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);
Run Code Online (Sandbox Code Playgroud)

使用此代码,我将rgb图像转换为灰度图像: 原始图像 灰度图像

希望这可以帮助