1

当我从图库或相机中选择图像时,我想将图像转换为 8 位。这是我必须尝试的代码。下面的代码在没有 alpha 通道的情况下工作。如果图像有 alpha,则它不起作用。当我从相机中挑选图像时,会出现一些 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];

我试过这段代码。此代码仅在图像 CGImageAlphaInfo 属性等于 kCGImageAlphaNoneSkipLast 时将图像转换为 8 位。

4

0 回答 0