web-dev-qa-db-fra.com

redimensionner l'image à une taille plus petite dans Swift3

J'essaie de mettre à l'échelle une image en cours de programmation graphique dans la galerie de photos. J'essaie de redimensionner l'image pour la réduire. Comment utiliser le code ci-dessous pour réduire l'image

   image1.scale
9
user7459574

Utilisez cette extension pour redimensionner votre image:

extension UIImage{

func resizeImageWith(newSize: CGSize) -> UIImage {

    let horizontalRatio = newSize.width / size.width
    let verticalRatio = newSize.height / size.height

    let ratio = max(horizontalRatio, verticalRatio)
    let newSize = CGSize(width: size.width * ratio, height: size.height * ratio)
    UIGraphicsBeginImageContextWithOptions(newSize, true, 0)
    draw(in: CGRect(Origin: CGPoint(x: 0, y: 0), size: newSize))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage!
    }


}

Fondamentalement, vous calculez le rapport d'aspect pour garder l'image intacte tout en la redimensionnant. Ensuite, vous obtenez le contexte d'image actuel et le dessinez dans le rectangle spécifié et le retournez enfin en tant que nouvelle image.

29
fja
 func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage {

    let scale = newWidth / image.size.width
    let newHeight = image.size.height * scale
    UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
    image.drawInRect(CGRectMake(0, 0, newWidth, newHeight))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}


@IBAction func chooseImage(sender: AnyObject) {


    var myPickerController = UIImagePickerController()
    myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    myPickerController.delegate = self;
    self.presentViewController(myPickerController, animated: true, completion: nil)


}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])

{
    var image = info[UIImagePickerControllerOriginalImage] as? UIImage
    let scaledImage:UIImage = resizeImage(image!, newWidth: 200)
    self.dismissViewControllerAnimated(true, completion: nil)

}

version Swift 4

extension UIImage {

    func resize(withWidth newWidth: CGFloat) -> UIImage? {

        let scale = newWidth / self.size.width
        let newHeight = self.size.height * scale
        UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
        self.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage
    }
}
4
Vinod Kumar

Cela peut être utile, cette méthode effectuera un redimensionnement proportionnel de l'image avec une bonne qualité.

func resizeImage(image: UIImage, withSize: CGSize) -> UIImage {

    var actualHeight: CGFloat = image.size.height
    var actualWidth: CGFloat = image.size.width
    let maxHeight: CGFloat = withSize.width
    let maxWidth: CGFloat = withSize.height
    var imgRatio: CGFloat = actualWidth/actualHeight
    let maxRatio: CGFloat = maxWidth/maxHeight
    let compressionQuality = 0.5//50 percent compression

    if (actualHeight > maxHeight || actualWidth > maxWidth) {
        if(imgRatio < maxRatio) {
            //adjust width according to maxHeight
            imgRatio = maxHeight / actualHeight
            actualWidth = imgRatio * actualWidth
            actualHeight = maxHeight
        } else if(imgRatio > maxRatio) {
            //adjust height according to maxWidth
            imgRatio = maxWidth / actualWidth
            actualHeight = imgRatio * actualHeight
            actualWidth = maxWidth
        } else {
            actualHeight = maxHeight
            actualWidth = maxWidth
        }
    }

    let rect: CGRect = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight)
    UIGraphicsBeginImageContext(rect.size)
    image.draw(in: rect)
    let image: UIImage  = UIGraphicsGetImageFromCurrentImageContext()!
    let imageData = UIImageJPEGRepresentation(image, CGFloat(compressionQuality))
    UIGraphicsEndImageContext()

    let resizedImage = UIImage(data: imageData!)
    return resizedImage!

}

Appelez ces méthodes comme ceci,

resizeImage(image: UIImage(named: "ImageName"), withSize: CGSize(width: 300, height: 300))

Merci:)

1

Essaye ça:

Première méthode:

func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage {

let scale = newWidth / image.size.width
let newHeight = image.size.height * scale
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
image.drawInRect(CGRectMake(0, 0, newWidth, newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

return newImage
}

Deuxième méthode:

import UIKit

func RBSquareImageTo(image: UIImage, size: CGSize) -> UIImage {
  return RBResizeImage(RBSquareImage(image), size)
}

func RBSquareImage(image: UIImage) -> UIImage {
  var originalWidth  = image.size.width
  var originalHeight = image.size.height

  var Edge: CGFloat
if originalWidth > originalHeight {
    Edge = originalHeight
} else {
    Edge = originalWidth
}

var posX = (originalWidth  - Edge) / 2.0
var posY = (originalHeight - Edge) / 2.0

var cropSquare = CGRectMake(posX, posY, Edge, Edge)

var imageRef = CGImageCreateWithImageInRect(image.CGImage, cropSquare);
return UIImage(CGImage: imageRef, scale: UIScreen.mainScreen().scale, orientation: image.imageOrientation)
 }

func RBResizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
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 = CGSizeMake(size.width * heightRatio, size.height * heightRatio)
} else {
    newSize = CGSizeMake(size.width * widthRatio,  size.height * widthRatio)
}

// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRectMake(0, 0, newSize.width, newSize.height)

// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.drawInRect(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

return newImage
  }

Référence:

  1. ici

  2. ici

1
Sour LeangChhean