Quantize Image, Save List of Remaining Colors

末鹿安然 提交于 2019-12-24 00:34:23

问题


Is there a library I can use that will allow me to 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.


回答1:


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.




回答2:


You can use ImageMagick for this task: https://github.com/marforic/imagemagick_lib_iphone MagickQuantizeImage and related function will help you.



来源:https://stackoverflow.com/questions/7474732/quantize-image-save-list-of-remaining-colors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!