从iPhone中的颜色阵列创建图像
问题描述:
我有一个颜色作为其对象的数组。我想从中创建一个图像。 实际上,发生的事情是,我正在获取图像中每个像素的像素值,修改它并将其对象存储在可变数组中。现在想从中画出一张图片。怎么做??任何想法???从iPhone中的颜色阵列创建图像
-(UIImage*)modifyPixels:(UIImage*)originalImage {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
NSMutableArray *result =[[NSMutableArray alloc]init];
int width = img.size.width;
int height = img.size.height;
originalImage = imageView.image;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc (height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height),img.CGImage);
CGContextRelease(context);
int byteIndex = 0;
for (int xx=0;xx<width;xx++){
for (int yy=0;yy<height;yy++){
// Now rawData contains the image data in the RGBA8888 pixel format.
NSLog(@"(%d,%d)",xx,yy);
NSLog(@"Alpha 255-Value is: %u", rawData[byteIndex + 3]);
NSLog(@"Red 255-Value is: %u", rawData[byteIndex]);
NSLog(@"Green 255-Value is: %u",rawData[byteIndex + 1]);
NSLog(@"Blue 255-Value is: %u",rawData[byteIndex + 2]);
CGFloat red = (rawData[byteIndex]+rawData[byteIndex + 1]+rawData[byteIndex + 2])/3;
CGFloat green = red;
CGFloat blue = red;
CGFloat alpha = 255;
byteIndex += 4;
UIColor *acolor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
[result addObject:acolor];
}
}
UIImage *newImage;
//CREATE NEW UIIMAGE (newImage) HERE from acolor(array of colors)
//this is the portion i'm in trouble with
return newImage;
[pool release];
}
答
据我了解,你尝试平均所有渠道。
你可以试试下面的方法,它使用核芯显卡:
CGImageRef inImage = mainImageView.image.CGImage;
CFDataRef dataRef = CGDataProviderCopyData(CGImageGetDataProvider(inImage));
UInt8* pixelBuffer = (UInt8*)CFDataGetBytePtr(dataRef);
int length = CFDataGetLength(dataRef);
for (int index = 0; index < length; index += 4)
{
pixelBuffer[index + 1] = (pixelBuffer[index + 1] + pixelBuffer[index + 2] + pixelBuffer[index + 3])/3.0;
pixelBuffer[index + 2] = pixelBuffer[index + 1];
pixelBuffer[index + 3] = pixelBuffer[index + 1];
}
CGContextRef ctx = CGBitmapContextCreate(pixelBuffer,
CGImageGetWidth(inImage),
CGImageGetHeight(inImage),
8,
CGImageGetBytesPerRow(inImage),
CGImageGetColorSpace(inImage),
kCGImageAlphaPremultipliedFirst);
CGImageRef imageRef = CGBitmapContextCreateImage(ctx);
UIImage* rawImage = [UIImage imageWithCGImage:imageRef];
CGContextRelease(ctx);
CFRelease(dataRef);
CGImageRelease(imageRef);
结果存储在rawImage
。您可以查看GLImageProcessing sample from Apple。
这显示了使用OpenGL的iPhone上的一些基本图像处理技术。
[池版本]是无法访问的代码,并导致泄漏。无论如何,该方法不应该需要自己的池。您也可以在Xcode项目中启用Clang静态分析工具。 (在组树中的'获取信息'在你的项目中 - >'运行静态分析器') – 2009-12-21 09:45:22