美文网首页图片处理
iOS图片比例压缩上传处理方案

iOS图片比例压缩上传处理方案

作者: SAW_ | 来源:发表于2017-03-30 19:28 被阅读251次

    先调整分辨率,分辨率可以自己设定一个值,大于的就缩小到这分辨率,小余的就保持原本分辨率。然后在判断图片数据大小,传入范围maxSize = 100 ,大于的再压缩,小的就保持原样

    - (NSData *)compressionImageToDataTargetWH:(CGFloat)targetWH maxFileSize:(NSInteger)maxFileSize  
    {  
        if (targetWH <= 0) {  
            targetWH = 1024;  
        }  
        //缩  
        CGSize newSize = CGSizeMake(self.size.width, self.size.height);  
        CGFloat tempHeight = newSize.height / targetWH;  
        CGFloat tempWidth = newSize.width / targetWH;  
        if (tempWidth > 1.0 && tempWidth > tempHeight) {  
            newSize = CGSizeMake(self.size.width / tempWidth, self.size.height / tempWidth);  
        }  
        else if (tempHeight > 1.0 && tempWidth < tempHeight){  
            newSize = CGSizeMake(self.size.width / tempHeight, self.size.height / tempHeight);  
        }  
        UIGraphicsBeginImageContext(newSize);  
        [self drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];  
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();  
        UIGraphicsEndImageContext();  
          
        //压  
        CGFloat compression = 0.9f;  
        CGFloat maxCompression = 0.1f;  
        NSData *imageData = UIImageJPEGRepresentation(newImage, compression);  
        while (imageData.length / 1000 > maxFileSize && compression > maxCompression) {  
            compression -= 0.1;  
            imageData = UIImageJPEGRepresentation(newImage, compression);  
        }  
          
        return imageData;  
    }  
    

    相关文章

      网友评论

        本文标题:iOS图片比例压缩上传处理方案

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