gpt4 book ai didi

iphone - 我可以编辑 UIImage 属性 CGImage 的像素吗

转载 作者:行者123 更新时间:2023-12-03 16:03:11 30 4
gpt4 key购买 nike

UIImage 有一个只读属性 CGImage。我必须将其像素读取到内存块并对其进行编辑,然后制作一个新的 UIImage 来替换旧的。我想知道是否有办法绕过只读属性并直接编辑这些像素。

谢谢。

<小时/>

谢谢大家。我找到了一种方法来做到这一点。使用这些方法编写一个类:

-(void)preProcess:(UIImage*)srcImage {
m_Context = ...// Created by calling CGBitmapContextCreate(...)
...
CGContextDrawImage(m_Context, rect, srcImage.CGImage);
m_Bits = (unsigned char*)CGBitmapContextGetData (mContext);
}

-(void)postProcess {
CGContextRelease(m_Context);
free(m_Bits);
}

-(UIImage*)doProcess:(CGPoint)pt {// just a example
unsigned char* ppxl = m_Bits + ...
// do something...
CGImageRef imRef = CGBitmapContextCreateImage(mContext);
return [UIImage imageWithCGImage:imRef];
}

并且 preProcess 和 postProcess 仅被调用一次。

最佳答案

您无法获取原始像素。不过,您可以获得一份副本。一种选择是按照 Matt 的建议进行操作,并将其转换为 PNG/JPG - 但请记住,图像现在已被压缩,您将直接操作压缩文件而不是像素。

如果您想获取原始像素的副本,您可以执行以下操作:

UIImage* image = ...; // An image
NSData* pixelData = (NSData*) CGDataProviderCopyData(CGImageGetDataProvider(image.CGImage));
void* pixelBytes = [pixelData bytes];

// Take away the red pixel, assuming 32-bit RGBA
for(int i = 0; i < [pixelData length]; i += 4) {
bytes[i] = 0; // red
bytes[i+1] = bytes[i+1]; // green
bytes[i+2] = bytes[i+2]; // blue
bytes[i+3] = bytes[i+3]; // alpha
}

现在,如果您想将其制作成新的 UIImage,您可以执行以下操作:

NSData* newPixelData = [NSData dataWithBytes:pixelBytes length:[pixelData length]];
UIImage* newImage = [UIImage imageWithData:newPixelData]; // Huzzah

关于iphone - 我可以编辑 UIImage 属性 CGImage 的像素吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1281210/

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