问题
I'm trying to figure out how to save a CGImageRef as JPEG2000.
At the moment I get scattered-looking image output.
I have the following code which works for every other format except kUTTypeJPEG2000. Saving as kUTTypeGIF or kUTTypePNG works fine. Interesting, saving as kUTTypeJPEG2000 without an alpha channel works too.
How can I get the image to output correctly?
- (void)saveImage:(CGImageRef)image path:(NSString *)path
{
// Set the image compression quality
CFMutableDictionaryRef properties = CFDictionaryCreateMutable(nil,
0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
// Save and finalize
CFURLRef url = CFBridgingRetain([[NSURL alloc] initFileURLWithPath:path]);
CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypeJPEG2000, 1, NULL);
CGImageDestinationAddImage(destination, image, properties);
CGImageDestinationFinalize(destination);
CFRelease(url);
}
回答1:
Fixed.
For the source image, instead of setting creating the context with the default bytes per row: CGImageGetBytesPerRow(image)
, we needed to specify 4 * width
.
size_t width = CGImageGetWidth(image);
size_t height = CGImageGetHeight(image);
size_t bytesPerRow = 4 * width;
CGContextRef context = CGBitmapContextCreate(NULL,
width,
height,
CGImageGetBitsPerComponent(image),
bytesPerRow,
CGImageGetColorSpace(image),
CGImageGetAlphaInfo(image));
来源:https://stackoverflow.com/questions/17556516/save-cgimageref-as-jpeg2000