gpt4 book ai didi

ios - 将 UIImage 转换为 8 位

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:17:50 26 4
gpt4 key购买 nike

我希望将 UIImage 转换为 8 位。我试图这样做,但我不确定我是否做对了,因为稍后当我尝试使用图像处理库 leptonica 时收到一条消息,指出它不是 8 位。任何人都可以告诉我我是否正确地执行此操作或如何执行此操作的代码?

谢谢!

代码

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

最佳答案

以下代码适用于没有 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);

使用这段代码,我将 rgb 图像转换为灰度图像: Original image Grayscale image

希望对你有帮助

关于ios - 将 UIImage 转换为 8 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17247542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com