美文网首页
ios 实现图片等比压缩

ios 实现图片等比压缩

作者: LinqingLv | 来源:发表于2015-12-11 17:11 被阅读1202次
压缩前图片
压缩前占用内存
压缩后图片
压缩后占用内存 压缩前后图片大小对比
class PictureUtil: NSObject {
   
    //尺寸压缩
    static func compress(image:UIImage,reWidth:CGFloat,reHeight:CGFloat)->NSData{
        
        UIGraphicsBeginImageContext(CGSizeMake(reWidth, reHeight))
        image.drawInRect(CGRectMake(0, 0, reWidth, reHeight))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        var inSameSize = getInSameSize(image, reWidth: reWidth, reHeight: reHeight)
        //如果尺寸没有超过 那么这里做些压的操作
        if inSameSize == 1.0{
            inSameSize = 0.7
        }
        return UIImageJPEGRepresentation(newImage, inSameSize)!
        
    }
    
    //获取体积缩放比例
    private static func getInSameSize(image:UIImage,reWidth:CGFloat,reHeight:CGFloat)->CGFloat{
        var insameSize:CGFloat = 1.0
        let width = image.size.width
        let height = image.size.height
        if (width > reWidth || height > reHeight){
            let halfWidth = width / 2
            let halfHeight = height / 2
            while ((halfWidth * insameSize) > reWidth && (halfHeight*insameSize) > reHeight){
                insameSize/=2
            }
        }
        
        return insameSize
        
    }
    
}

相关文章

网友评论

      本文标题:ios 实现图片等比压缩

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