Reduce UIImage size to a manageable size (reduce bytes)

前端 未结 5 1603
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 16:00

I want to reduce the number of bytes of an image captured by the device, since i believe the _imageScaledToSize does not reduce the number of bytes of the pictu

5条回答
  •  时光取名叫无心
    2020-12-05 17:00

    UIImageJPEGRepresentation does the trick but I find that using the ImageIO framework often gets significantly better compression results for the same quality setting. It may be slower, but depending on your use case this may not be an issue.

    (Code adapted for NSData from this blog post by Zachary West).

    #import 
    #import 
    
    ...
    
    + (NSData*)JPEGDataFromImage:(UIImage*)image quality:(double)quality
    {
        CFMutableDataRef outputImageDataRef = CFDataCreateMutable(kCFAllocatorDefault, 0);
        CGImageDestinationRef imageDestinationRef = CGImageDestinationCreateWithData(outputImageDataRef, kUTTypeJPEG, 1, NULL);
    
        NSDictionary* properties = @{
            (__bridge NSString*)kCGImageDestinationLossyCompressionQuality: @(quality)
        };
        CGImageDestinationSetProperties(imageDestinationRef, (__bridge CFDictionaryRef)properties);
    
        CGImageDestinationAddImage(imageDestinationRef, image.CGImage, NULL);
    
        CGImageDestinationFinalize(imageDestinationRef);
    
        CFRelease(imageDestinationRef);
    
        NSData* imageData = CFBridgingRelease(outputImageDataRef);
        return imageData;
    }
    

提交回复
热议问题