目标c - 如何以保存方式编程设置JPEG文件的UIImage DPI

Pat*_*cia 3 metadata objective-c uiimage

我已经读过您可以更改图像的元数据以将dpi设置为默认值72以外的其他值.我在此问题中尝试了解决方案,但遇到的问题与该问题的作者相同.原始图像中的图像元数据属性似乎优先于修改.

我正在使用ALAssetsLibrary将图像写入iPhone上的照片库.我需要dpi而不是标准的72dpi.我知道可以通过直接操作位来更改属性(如此处所示),但我希望iOS提供更好的解决方案.

预先感谢您的帮助.

moh*_*acs 7

这段代码用于处理图像元数据 - 如果存在 - 您可以使用它来更改图像元数据中的任何值.请注意,更改元数据中的DPI值实际上不会处理图像并更改DPI.

#import <ImageIO/ImageIO.h>


-(NSData *)changeMetaDataInImage
{
    NSData *sourceImageData = [[NSData alloc] initWithContentsOfFile:@"~/Desktop/1.jpg"];
    if (sourceImageData != nil)
    {
        CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)sourceImageData, NULL);

        NSDictionary *metadata = (__bridge_transfer NSDictionary *)CGImageSourceCopyPropertiesAtIndex(source, 0, NULL);

        NSMutableDictionary *tempMetadata = [metadata mutableCopy];
        [tempMetadata setObject:[NSNumber numberWithInt:300] forKey:@"DPIHeight"];
        [tempMetadata setObject:[NSNumber numberWithInt:300] forKey:@"DPIWidth"];

        NSMutableDictionary *EXIFDictionary = [[tempMetadata objectForKey:(NSString *)kCGImagePropertyTIFFDictionary] mutableCopy];
        [EXIFDictionary setObject:[NSNumber numberWithInt:300] forKey:(NSString *)kCGImagePropertyTIFFXResolution];
        [EXIFDictionary setObject:[NSNumber numberWithInt:300] forKey:(NSString *)kCGImagePropertyTIFFYResolution];

        NSMutableDictionary *JFIFDictionary = [[NSMutableDictionary alloc] init];
        [JFIFDictionary setObject:[NSNumber numberWithInt:300] forKey:(NSString *)kCGImagePropertyJFIFXDensity];
        [JFIFDictionary setObject:[NSNumber numberWithInt:300] forKey:(NSString *)kCGImagePropertyJFIFYDensity];
        [JFIFDictionary setObject:@"1" forKey:(NSString *)kCGImagePropertyJFIFVersion];

        [tempMetadata setObject:EXIFDictionary forKey:(NSString *)kCGImagePropertyTIFFDictionary];
        [tempMetadata setObject:JFIFDictionary forKey:(NSString *)kCGImagePropertyJFIFDictionary];

        NSMutableData *destinationImageData = [NSMutableData data];

        CFStringRef UTI = CGImageSourceGetType(source);

        CGImageDestinationRef destination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)destinationImageData, UTI, 1, NULL);

        CGImageDestinationAddImageFromSource(destination, source,0, (__bridge CFDictionaryRef) tempMetadata);

        CGImageDestinationFinalize(destination);

        return destinationImageData;
    }
}
Run Code Online (Sandbox Code Playgroud)