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以上的版本,系統(tǒng)提供了一個方法直接轉換

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;
}
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容