【问题标题】:How to convert from CGImageRef to GraphicsMagick Blob type?如何从 CGImageRef 转换为 GraphicsMagick Blob 类型?
【发布时间】:2013-07-05 02:30:45
【问题描述】:

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

我希望将其转换为 GraphicsMagick Blob (http://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]);
}

【问题讨论】:

    标签: objective-c core-graphics graphicsmagick


    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 2013-12-15
      • 2018-08-05
      • 2015-04-30
      • 2013-05-09
      • 2015-10-10
      • 1970-01-01
      • 1970-01-01
      • 2017-11-28
      • 1970-01-01
      相关资源
      最近更新 更多