UIImage有一个只读属性CGImage。我必须将其像素读取到内存块并对其进行编辑,然后制作一个新的 UIImage 来替换旧的。我想知道是否有办法绕过只读属性并直接编辑这些像素。
Thanks.
谢谢大家。我找到了一种方法来做到这一点。使用这些方法编写一个类:
-(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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)