2013-07-05 32 views
1

我有一個相當標準的RGBA圖像作爲CGImageRef。如何轉換CGImageRef至GraphicsMagick Blob類型?

我期待將其轉換成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

所需先獲得正確的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);