Juste un partage d’une méthode trouvée aujourd’hui sur Stakoverflow (j’ai oublié de mettre le lien en marque page).
Donc, si vous voulez réduire la taille d’une image, pour la mettre sur un serveur en ligne, ou simplement réduire l’espace disque utilisé, vous pouvez utiliser cette fonction :
——————————– Code ———————————-
import UIKit
func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
// usage :
// self.resizeImage(UIImage(named: « yourImageName »)!, targetSize: CGSizeMake(200.0, 200.0))
let size = image.size
let widthRatio = targetSize.width / image.size.width
let heightRatio = targetSize.height / image.size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
} else {
newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
}
// This is the rect that we’ve calculated out and this is what is actually used below
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
——————————– / Code ———————————-
Ensuite, elle s’utilise comme cela (bien sûr, remplacer les valeurs 200.0 par la taille finale désirée) :
self.resizeImage(UIImage(named: « yourImageName »)!, targetSize: CGSizeMake(200.0, 200.0))
L’intérêt de cette méthode est qu’elle conserve les proportions de l’image.