美文网首页
根据给出的字节大小压缩图片

根据给出的字节大小压缩图片

作者: CY水漆 | 来源:发表于2024-03-14 10:37 被阅读0次

项目中微信分享需求,微信官方给出图片不能过大,经测试当图片大于1M时(1024*1024),微信会报错,导致有些图片过大必须做压缩处理,本方法使用的事二分法加图片绘制,比寻常的循环压缩要快,本人亲测有效,代码直接粘贴复制即可使用

- (UIImage*)compressImageSize:(UIImage*)imagetoByte:(NSUInteger)maxLength {

    UIImage*resultImage = image;

    NSData *data = UIImageJPEGRepresentation(resultImage, 1);

    NSUIntegerlastDataLength =0;

    while(data.length> maxLength && data.length!= lastDataLength) {

        lastDataLength = data.length;

        CGFloatratio = (CGFloat)maxLength / data.length;

        CGSizesize =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 

        [resultImagedrawInRect:CGRectMake(0,0, size.width, size.height)];

        resultImage =UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();

        data =UIImageJPEGRepresentation(resultImage,1);

    }

    returnresultImage;

}

相关文章

网友评论

      本文标题:根据给出的字节大小压缩图片

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