美文网首页
图片压缩 不大于指定大小

图片压缩 不大于指定大小

作者: 失忆的程序员 | 来源:发表于2021-06-18 17:30 被阅读0次
    ///
    - (NSData *)compressBySizeWithMaxLength:(NSUInteger)maxLength img:(UIImage *)resultImage
    {
        
        NSData *data = UIImageJPEGRepresentation(resultImage, 1);
        NSUInteger lastDataLength = 0;
        while (data.length > maxLength && data.length != lastDataLength) {
            lastDataLength = data.length;
            CGFloat ratio = (CGFloat)maxLength / data.length;
            CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)), (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
            UIGraphicsBeginImageContext(size);
            // Use image to draw (drawInRect:), image is larger but more compression time
            // Use result image to draw, image is smaller but less compression time
            [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
            resultImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            data = UIImageJPEGRepresentation(resultImage, 1);
        }
        return data;
    }
    
    
    
    /// 压缩
    - (UIImage *)compressImageQuality:(UIImage *)image toByte:(NSInteger)maxLength {
        CGFloat compression = 1;
        NSData *data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength) return image;
        CGFloat max = 1;
        CGFloat min = 0;
        for (int i = 0; i < 6; ++i) {
            compression = (max + min) / 2;
            data = UIImageJPEGRepresentation(image, compression);
            if (data.length < maxLength * 0.9) {
                min = compression;
            } else if (data.length > maxLength) {
                max = compression;
            } else {
                break;
            }
        }
        UIImage *resultImage = [UIImage imageWithData:data];
        return resultImage;
    }
    
    
    

    相关文章

      网友评论

          本文标题:图片压缩 不大于指定大小

          本文链接:https://www.haomeiwen.com/subject/dcclyltx.html