转换UIImage到NSData不使用UIImagePngrepresentation或UIImageJpegRepre



我需要将UIImage转换为NSData,但不使用UIImagePngRepresentationUIImageJpegRepresentation,对于来自photolib的图像,我可以使用这里提到的assetlib方法使用ALAssetsLibrary和ALAsset取出图像作为NSData,但对于捕获的图像,资产url不存在,因此在这种情况下,我需要将UIImage直接转换为具有exif数据的字节,我怎么能做到这一点?请帮助

我也遇到过类似的问题,但出于安全原因,我不想像Wes建议的那样将数据写入默认文件系统。我还希望能够向我的图像添加元数据。我的解决方案如下:

- (NSData *)dataFromImage:(UIImage *)image metadata:(NSDictionary *)metadata mimetype:(NSString *)mimetype
{
    NSMutableData *imageData = [NSMutableData data];
    CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, (__bridge CFStringRef)mimetype, NULL);
    CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)imageData, uti, 1, NULL);
    if (imageDestination == NULL)
    {
        NSLog(@"Failed to create image destination");
        imageData = nil;
    }
    else
    {
        CGImageDestinationAddImage(imageDestination, image.CGImage, (__bridge CFDictionaryRef)metadata);
        if (CGImageDestinationFinalize(imageDestination) == NO)
        {
            NSLog(@"Failed to finalise");
            imageData = nil;
        }
        CFRelease(imageDestination);
    }
    CFRelease(uti);
    return imageData;
}

要使用它,您可以这样做:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSDictionary *metadata = [info objectForKey:UIImagePickerControllerMediaMetadata];
    NSString *mimeType = @"image/jpeg"; // ideally this would be dynamically set. Not defaulted to a jpeg!
    // you could add to the metadata dictionary (after converting it to a mutable copy) if you needed to.
    // convert to NSData
    NSData *imageData = [self dataFromImage:image metadata:metadata mimetype:mimeType];
    // ...
}

H Bastan,

根据你的评论:

…我想通过UIImagepicker委托方法在文档目录中保存设备相机返回的捕获图像…

看起来你的真正的目标是将带有EXIF数据的图像保存到文档目录,而不是明确地将UIImage作为带有EXIF数据的NSData对象。在这种情况下,您可以在imagePickerController:didFinishPickingMediaWithInfo:

的实现中执行以下操作
// Get your image.
UIImage *capturedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
// Get your metadata (includes the EXIF data).
NSDictionary *metadata = [info objectForKey:UIImagePickerControllerMediaMetadata];
// Create your file URL.
NSFileManager *defaultManager = [NSFileManager defaultManager];
NSURL *docsURL = [[defaultManager URLsForDirectory:NSDocumentDirectory
                                         inDomains:NSUserDomainMask] lastObject];
NSURL *outputURL = [docsURL URLByAppendingPathComponent:@"imageWithEXIFData.jpg"];
// Set your compression quuality (0.0 to 1.0).
NSMutableDictionary *mutableMetadata = [metadata mutableCopy];
[mutableMetadata setObject:@(1.0) forKey:(__bridge NSString *)kCGImageDestinationLossyCompressionQuality];
// Create an image destination.
CGImageDestinationRef imageDestination = CGImageDestinationCreateWithURL((__bridge CFURLRef)outputURL, kUTTypeJPEG , 1, NULL);
if (imageDestination == NULL ) {
    // Handle failure.
    NSLog(@"Error -> failed to create image destination.");
    return;
}
// Add your image to the destination.
CGImageDestinationAddImage(imageDestination, capturedImage.CGImage, (__bridge CFDictionaryRef)mutableMetadata);
// Finalize the destination.
if (CGImageDestinationFinalize(imageDestination) == NO) {
    // Handle failure.
    NSLog(@"Error -> failed to finalize the image.");
}
CFRelease(imageDestination);

从我的测试来看,执行时间与执行

相同或更快:
NSData *data = UIImageJPEGRepresentation(capturedImage, 1.0);
[data writeToURL:outputURL atomically:YES];

…并且您可以保留EXIF数据!

如果你想确保你的UI保持响应,你也可以将它调度到后台队列:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    // Do the image saving here...
});

重要提示:您需要将ImageIO.frameworkMobileCoreServices.framework添加到目标的构建阶段,并将它们导入到您进行图像保存的类中:

#import <ImageIO/ImageIO.h>
#import <MobileCoreServices/MobileCoreServices.h>

其他notes 这是我的理解,在这种情况下,我们没有创建一个世代损失时,保存图像的建议在示例中。我们正在使用UIImage的CGImage属性,如文档所述:

底层石英图像数据

您可以尝试这样做。我不确定这是不是最好的方法。但值得一试。如果图像URL可用,您可以尝试initWithContentsOfUrl

NSData *data = [[NSData alloc]initWithContentsOfFile:@"/Users/test/isajf/isajf/test.jpg"];

相关内容

  • 没有找到相关文章

最新更新