如何从CGImageRef转换为GraphicsMagick Blob类型? [英] How to convert from CGImageRef to GraphicsMagick Blob type?

查看:88
本文介绍了如何从CGImageRef转换为GraphicsMagick Blob类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a fairly standard RGBA image as a CGImageRef.

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

I'm looking to convert this into a GraphicsMagick Blob (http://www.graphicsmagick.org/Magick++/Image.html#blobs)

换位的最佳方法是什么?

What's the best way to go about transposing it?

我有这个但是如果我在 pathString 中指定PNG8,它只会产生纯黑色图像,否则会崩溃:

I have this but it produces only a plain black image if I specify PNG8 in the pathString or it crashes:

- (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]);
}


推荐答案

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

Needed to get the image in the right RGBA format first. The original CGImageRef had a huge number of bytes per row. Creating a context with only 4 bytes per pixel did the trick.

// 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);

这篇关于如何从CGImageRef转换为GraphicsMagick Blob类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆