@implementation UIImage (NegativeImage)- (UIImage *)negativeImage{ // get wIDth and height as integers,since we'll be using them as // array subscripts,etc,and this'll save a whole lot of casting CGSize size = self.size; int wIDth = size.wIDth; int height = size.height; // Create a suitable RGB+Alpha bitmap context in BGRA colour space CGcolorSpaceRef colourSpace = CGcolorSpaceCreateDeviceRGB(); unsigned char *memoryPool = (unsigned char *)calloc(wIDth*height*4,1); CGContextRef context = CGBitmapContextCreate(memoryPool,wIDth,height,8,wIDth * 4,colourSpace,kCGBitmapByteOrder32Big | kCGImageAlphaPremultiplIEdLast); CGcolorSpaceRelease(colourSpace); // draw the current image to the newly created context CGContextDrawImage(context,CGRectMake(0,height),[self CGImage]); // run through every pixel,a scan line at a time... for(int y = 0; y < height; y++) { // get a pointer to the start of this scan line unsigned char *linePointer = &memoryPool[y * wIDth * 4]; // step through the pixels one by one... for(int x = 0; x < wIDth; x++) { // get RGB values. We're dealing with premultiplIEd Alpha // here,so we need to divIDe by the Alpha channel (if it // isn't zero,of course) to get uninflected RGB. We // multiply by 255 to keep precision while still using // integers int r,g,b; if(linePointer[3]) { r = linePointer[0] * 255 / linePointer[3]; g = linePointer[1] * 255 / linePointer[3]; b = linePointer[2] * 255 / linePointer[3]; } else r = g = b = 0; // perform the colour inversion r = 255 - r; g = 255 - g; b = 255 - b; // multiply by Alpha again,divIDe by 255 to undo the // scaling before,store the new values and advance // the pointer we're reading pixel data from linePointer[0] = r * linePointer[3] / 255; linePointer[1] = g * linePointer[3] / 255; linePointer[2] = b * linePointer[3] / 255; linePointer += 4; } } // get a CG image from the context,wrap that into a // UIImage CGImageRef cgImage = CGBitmapContextCreateImage(context); UIImage *returnImage = [UIImage imageWithCGImage:cgImage]; // clean up CGImageRelease(cgImage); CGContextRelease(context); free(memoryPool); // and return return returnImage;}@end
所以这样添加一个类别方法给UIImage:
>创建一个清晰的CoreGraphics位图上下文,可以访问它的内存把UIImage拉到它>遍历每个像素,从预乘α转换为未反映的RGB,分别反转每个通道,再次乘以Alpha并存储回>从上下文获取图像并将其包装成UIImage>自己清理,并返回UIImage
总结以上是内存溢出为你收集整理的iphone – 以编程方式反转图像的颜色可能吗?全部内容,希望文章能够帮你解决iphone – 以编程方式反转图像的颜色可能吗?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)