美文网首页
压缩图片

压缩图片

作者: 请叫我魔法师 | 来源:发表于2018-04-27 08:01 被阅读0次
    - (NSData *)reSizeImageData:(UIImage *)sourceImage maxImageSize:(CGFloat)maxImageSize maxSizeWithKB:(CGFloat) maxSize{
        
        if (maxSize <= 0.0) maxSize = 1024.0;
        if (maxImageSize <= 0.0) maxImageSize = 1024.0;
        
        //先调整分辨率
        CGSize newSize = CGSizeMake(sourceImage.size.width, sourceImage.size.height);
        
        CGFloat tempHeight = newSize.height / maxImageSize;
        CGFloat tempWidth = newSize.width / maxImageSize;
        
        if (tempWidth > 1.0 && tempWidth > tempHeight) {
            newSize = CGSizeMake(sourceImage.size.width / tempWidth, sourceImage.size.height / tempWidth);
        }
        else if (tempHeight > 1.0){
            newSize = CGSizeMake(sourceImage.size.width / tempHeight, sourceImage.size.height / tempHeight);
        }
        
        UIGraphicsBeginImageContext(newSize);
        [sourceImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        //调整大小
        NSData *imageData = UIImageJPEGRepresentation(newImage,1.0);
        CGFloat sizeOriginKB = imageData.length / 1024.0;
        
        CGFloat resizeRate = 0.9;
        while (sizeOriginKB > maxSize && resizeRate > 0.1) {
            imageData = UIImageJPEGRepresentation(newImage,resizeRate);
            sizeOriginKB = imageData.length / 1024.0;
            resizeRate -= 0.1;
        }
        
        return imageData;
    }
    

    相关文章

      网友评论

          本文标题:压缩图片

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