我有一个以颜色为对象的数组。我想用它创建一个图像。 实际上,发生的事情是,我正在获取图像每个像素的像素值,修改它并将其对象存储在可变数组中。现在想从中绘制图像。怎么做??有什么想法吗???
-(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];
}
最佳答案
据我了解,您尝试平均所有 channel 。
您可以尝试以下使用 Core Graphics 的方法:
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 .
这展示了 iPhone 上使用 OpenGL 的一些基本图像处理技术。
关于iphone - 从 iPhone 中的一系列颜色创建图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1938617/