Swift 图片压缩

func compressionImage(image: UIImage, compressionQuality: CGFloat) -> Data? {

    //实现等比例缩放
    let hfactor = image.size.width / screenWidth;
    let vfactor = image.size.height / screenHeight;
    let factor = fmax(hfactor, vfactor);
    //画布大小
    let newWith: CGFloat = image.size.width / factor
    let newHeigth: CGFloat = image.size.height / factor
    let newSize = CGSize(width: newWith, height: newHeigth)
    
    UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.main.scale)
    image.draw(in: CGRect(x: 0, y: 0, width: newWith, height: newHeigth))
    
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    
    if let compressionImage = newImage {
        //图像压缩
        let newImageData = UIImageJPEGRepresentation(compressionImage, compressionQuality)
        if let data = newImageData {
            return data
        }
    }
    
    return nil
}

猜你喜欢

转载自my.oschina.net/u/1763048/blog/1622466