如何转换CGImageRef至GraphicsMagick Blob类型?

时间:2013-07-05 02:30:45

标签: objective-c core-graphics graphicsmagick

我有一个相当标准的RGBA图像作为CGImageRef。

我希望将其转换为GraphicsMagick Blobhttp://www.graphicsmagick.org/Magick++/Image.html#blobs

转换它的最佳方法是什么?

我有这个,但如果我在pathString中指定PNG8或者它崩溃了,它只产生一个普通的黑色图像:

- (void)saveImage:(CGImageRef)image path:(NSString *)pathString
{
    CGDataProviderRef dataProvider = CGImageGetDataProvider(image);
    NSData *data = CFBridgingRelease(CGDataProviderCopyData(dataProvider));
    const void *bytes = [data bytes];

    size_t width = CGImageGetWidth(image);
    size_t height = CGImageGetHeight(image);
    size_t length = CGImageGetBytesPerRow(image) * height;

    NSString *sizeString = [NSString stringWithFormat:@"%ldx%ld", width, height];

    Image pngImage;
    Blob blob(bytes, length);

    pngImage.read(blob);
    pngImage.size([sizeString UTF8String]);
    pngImage.magick("RGBA");
    pngImage.write([pathString UTF8String]);
}

1 个答案:

答案 0 :(得分:1)

首先需要以正确的RGBA格式获取图像。原始的CGImageRef每行有大量的字节。创建一个每像素只有4个字节的上下文就可以了。

// Calculate the image width, height and bytes per row
size_t width = CGImageGetWidth(image);
size_t height = CGImageGetHeight(image);
size_t bytesPerRow = 4 * width;
size_t length = bytesPerRow * height;

// Set the frame
CGRect frame = CGRectMake(0, 0, width, height);

// Create context
CGContextRef context = CGBitmapContextCreate(NULL,
                                             width,
                                             height,
                                             CGImageGetBitsPerComponent(image),
                                             bytesPerRow,
                                             CGImageGetColorSpace(image),
                                             kCGImageAlphaPremultipliedLast);

if (!context) {
    return;
}

// Draw the image inside the context
CGContextSetBlendMode(context, kCGBlendModeCopy);
CGContextDrawImage(context, frame, image);

// Get the bitmap data from the context
void *bytes = CGBitmapContextGetData(context);