美文网首页
图片压缩------微信分享(图片不能大于32kb否则调不起微信

图片压缩------微信分享(图片不能大于32kb否则调不起微信

作者: 恩哼恩哼蹦擦擦GH | 来源:发表于2019-04-19 14:57 被阅读0次

    /*根据url返回UIimage*/

    +(UIImage*) getImageFromURL:(NSString*)fileURL

    {

        UIImage* result;

        NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];

        result = [UIImageimageWithData:data];

        returnresult;

    }

    #pragma mark - 压缩图片---小于32KB

    + (UIImage*)compressImage:(UIImage*)image toByte:(NSUInteger)maxLength {

        // Compress by quality

        CGFloatcompression =1;

        NSData*data =UIImageJPEGRepresentation(image, compression);

        if(data.length< maxLength)returnimage;

        CGFloatmax =1;

        CGFloatmin =0;

        for(inti =0; i <6; ++i) {

            compression = (max + min) /2;

            data =UIImageJPEGRepresentation(image, compression);

            if(data.length< maxLength *0.9) {

                min = compression;

            }elseif(data.length> maxLength) {

                max = compression;

            }else{

                break;

            }

        }

        UIImage*resultImage = [UIImageimageWithData:data];

        if(data.length< maxLength)returnresultImage;

        // Compress by size

        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);

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

            resultImage =UIGraphicsGetImageFromCurrentImageContext();

            UIGraphicsEndImageContext();

            data =UIImageJPEGRepresentation(resultImage, compression);

        }

        returnresultImage;

    }

    相关文章

      网友评论

          本文标题:图片压缩------微信分享(图片不能大于32kb否则调不起微信

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