Swift 4で、私はこの拡張機能を作成しました。この拡張機能は、期待されるサイズを受け取り、それに到達しようとします。
extension UIImage {
enum CompressImageErrors: Error {
case invalidExSize
case sizeImpossibleToReach
}
func compressImage(_ expectedSizeKb: Int, completion : (UIImage,CGFloat) -> Void ) throws {
let minimalCompressRate :CGFloat = 0.4
if expectedSizeKb == 0 {
throw CompressImageErrors.invalidExSize
}
let expectedSizeBytes = expectedSizeKb * 1024
let imageToBeHandled: UIImage = self
var actualHeight : CGFloat = self.size.height
var actualWidth : CGFloat = self.size.width
var maxHeight : CGFloat = 841
var maxWidth : CGFloat = 594
var imgRatio : CGFloat = actualWidth/actualHeight
let maxRatio : CGFloat = maxWidth/maxHeight
var compressionQuality : CGFloat = 1
var imageData:Data = UIImageJPEGRepresentation(imageToBeHandled, compressionQuality)!
while imageData.count > expectedSizeBytes {
if (actualHeight > maxHeight || actualWidth > maxWidth){
if(imgRatio < maxRatio){
imgRatio = maxHeight / actualHeight;
actualWidth = imgRatio * actualWidth;
actualHeight = maxHeight;
}
else if(imgRatio > maxRatio){
imgRatio = maxWidth / actualWidth;
actualHeight = imgRatio * actualHeight;
actualWidth = maxWidth;
}
else{
actualHeight = maxHeight;
actualWidth = maxWidth;
compressionQuality = 1;
}
}
let rect = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight)
UIGraphicsBeginImageContext(rect.size);
imageToBeHandled.draw(in: rect)
let img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if let imgData = UIImageJPEGRepresentation(img!, compressionQuality) {
if imgData.count > expectedSizeBytes {
if compressionQuality > minimalCompressRate {
compressionQuality -= 0.1
} else {
maxHeight = maxHeight * 0.9
maxWidth = maxWidth * 0.9
}
}
imageData = imgData
}
}
completion(UIImage(data: imageData)!, compressionQuality)
}
}
使用するには
do {
try UiImageView.image?.compressImage(100, completion: { (image, compressRatio) in
print(image.size)
imageData = UIImageJPEGRepresentation(image, compressRatio)
base64data = imageData?.base64EncodedString()
})
} catch {
print("Error")
}