iOS/swift之图片压缩、拉伸

1.********图片压缩******

方法一:
 //压缩图片
            let newSize:CGSize = CGSize.init(width: 50, height: 50)
            UIGraphicsBeginImageContext(newSize)
            image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
            
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()






方法二:
/**
     *  压缩上传图片到指定字节
     *
     *  image     压缩的图片
     *  maxLength 压缩后最大字节大小
     *
     *  return 压缩后图片的二进制
     */
    func compressImage(image: UIImage, maxLength: Int) -> NSData? {
        
        let newSize = self.scaleImage(image, imageLength: 300)
        let newImage = self.resizeImage(image, newSize: newSize)
        
        var compress:CGFloat = 0.9
        var data = UIImageJPEGRepresentation(newImage, compress)
        
        while data?.length > maxLength && compress > 0.01 {
            compress -= 0.02  
            data = UIImageJPEGRepresentation(newImage, compress)
        }
        
        return data
    }

3.*******图片拉升********

var normal = UIImage(named: name)! 
        let imageWidth = normal.size.width * 0.5
        let imageHeight = normal.size.height * 0.5  
        normal = resizableImageWithCapInsets(UIEdgeInsetsMake(imageHeight, imageWidth, imageHeight, imageWidth))

猜你喜欢

转载自blog.csdn.net/u011146511/article/details/86509621