iOS 将UIImage转换成NSData(PNG\JPEG\HEIC\TIFF)

有时候需要将UIImage对象转成NSData去处理。常用的是
1.转换成JPEGData

  NSData * data = UIImageJPEGRepresentation(image, 1);

2.转换成PNGData

  NSData * data = UIImagePNGRepresentation(image);

如果想转换成其它格式的NSData,则需要用到CGImageDestination相关的处理。

3.转换成HEICData

#import <ImageIO/ImageIO.h>
 - (NSMutableData *)imageToHEICData:(UIImage *)image {
    // 1. 将 UIImage 转换为 HEIF 格式的 NSData(保留 HEIF 格式)
    NSMutableData *heifData = [NSMutableData data];
    CFStringRef heifType = CFSTR("public.heic");
    CGImageDestinationRef destination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)heifData, heifType, 1, NULL);
    
    if (!destination) {
        return nil;
    }
    
    // 2. 添加元数据到 HEIF 数据
    CGImageDestinationAddImage(destination, image.CGImage, NULL);
    CGImageDestinationFinalize(destination);
    CFRelease(destination);
    
    return heifData;
}

另外,在iOS17以上的版本,系统提供了一个方法直接转换

NSData * data = UIImageHEICRepresentation(image);

4.转换成TIFF类型Data

#import <ImageIO/ImageIO.h>
- (NSMutableData *)imageToTiffData:(UIImage *)image {
    // 生成TIFF数据
    NSMutableData * tiffData = [NSMutableData data];
    
    CGImageDestinationRef destination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)tiffData,kUTTypeTIFF,1,NULL);
    
    if (!destination) {
        return nil;
    }
    
    // 2. 添加元数据到 TIFF 数据
    CGImageDestinationAddImage(destination, image.CGImage, NULL);
    CGImageDestinationFinalize(destination);
    CFRelease(destination);
    
    return tiffData;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容