Swift 圖片壓縮

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

//實現等比例縮放
    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
}
相關文章
相關標籤/搜索