Quantize Image, Save List of Remaining Colors
Is there a library I can use that will allow me t开发者_运维技巧o quantize images on an iPhone?
I want to quantize the images down to maybe 8 colors and record either hex or rgb values for each color remaining after the quantization.
Shouldn't be too hard to do this yourself. Get to the pixel data and then just iterate through and quantize. Here's how to get the pixel data:
(This code is from Erica Sadun's Cookbook samples, I believe)
// Courtesy of Apple, Create Bitmap with Alpha/RGB values
CGContextRef CreateARGBBitmapContext (CGImageRef inImage, CGSize size)
{
CGContextRef context = NULL;
CGColorSpaceRef colorSpace;
void * bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;
size_t pixelsWide = size.width;
size_t pixelsHigh = size.height;
bitmapBytesPerRow = (pixelsWide * 4);
bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);
colorSpace = CGColorSpaceCreateDeviceRGB();
if (colorSpace == NULL)
{
fprintf(stderr, "Error allocating color space\n");
return NULL;
}
// allocate the bitmap & create context
bitmapData = malloc( bitmapByteCount );
if (bitmapData == NULL)
{
fprintf (stderr, "Memory not allocated!");
CGColorSpaceRelease( colorSpace );
return NULL;
}
context = CGBitmapContextCreate (bitmapData, pixelsWide, pixelsHigh, 8,
bitmapBytesPerRow, colorSpace,
kCGImageAlphaPremultipliedFirst);
if (context == NULL)
{
free (bitmapData);
fprintf (stderr, "Context not created!");
}
CGColorSpaceRelease( colorSpace );
return context;
}
// Return a C-based bitmap of the image data inside an image
unsigned char *RequestImagePixelData(UIImage *inImage)
{
CGImageRef img = [inImage CGImage];
CGSize size = [inImage size];
CGContextRef cgctx = CreateARGBBitmapContext(img, size);
if (cgctx == NULL) return NULL;
CGRect rect = {{0,0},{size.width, size.height}};
CGContextDrawImage(cgctx, rect, img);
unsigned char *data = CGBitmapContextGetData (cgctx);
CGContextRelease(cgctx);
return data;
}
RequestImagePixelData will return an array where each pixel is described as 8 bits of alpha, 8 bits of red, 8 bits of green and 8 bits of blue.
You can use ImageMagick for this task: https://github.com/marforic/imagemagick_lib_iphone MagickQuantizeImage and related function will help you.
精彩评论