有时候需要将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;
}