将UIImage调整为200x200pt / px

时间:2015-08-12 13:37:59

标签: ios swift uiimage

我一直在努力调整图片大小。 基本上我已经弄明白了: How to scale down a UIImage and make it crispy / sharp at the same time instead of blurry?

这似乎是一个合法的解决方案,但不知怎的,它无法正常工作。

我的应用可以使用相机胶卷中的照片。这张照片应调整到大约200x200,而宽度很重要,而不是高度。

不幸的是,我没有一个示例代码,因为我对我的愤怒无法解决非工作解决方案,抱歉。

12 个答案:

答案 0 :(得分:141)

这是我的代码。图像的宽度为850像素,而不是200像素:

 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 imagenow = info[UIImagePickerControllerOriginalImage] as? UIImage

    imageImage.image = resizeImage(imagenow!, newWidth: 200)



    pimg2 = imageImage.image!

    cidnew2 = textFieldCID!.text!
    pname2 = textFieldName!.text
    pmanu2 = textFieldMan!.text
    pnick2 = textFieldNick!.text
    podate2 = textFieldPODate!.text
    pno2 = textFieldArtNo!.text



    self.dismissViewControllerAnimated(true, completion: nil)

}

答案 1 :(得分:57)

基于swift_dan的回答,Swift 3的更新

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

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

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}

答案 2 :(得分:37)

如果您正在处理包含透明胶片的PNG图像,则接受的答案功能实际上会将透明区域转换为黑色。

如果您希望缩放并保持透明胶片的位置,请尝试以下功能:

SWIFT 4

extension UIImage {
    func scaleImage(toSize newSize: CGSize) -> UIImage? {
        var newImage: UIImage?
        let newRect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height).integral
        UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
        if let context = UIGraphicsGetCurrentContext(), let cgImage = self.cgImage {
            context.interpolationQuality = .high
            let flipVertical = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: newSize.height)
            context.concatenate(flipVertical)
            context.draw(cgImage, in: newRect)
            if let img = context.makeImage() {
                newImage = UIImage(cgImage: img)
            }
            UIGraphicsEndImageContext()
        }
        return newImage
    }
}

答案 3 :(得分:21)

  

对于Swift 3.0

只需将此代码段添加为UIImage的扩展名即可。但是,请记住,不会以正方形形式制作图像,但如果采用该形式,则结果将为正方形。

extension UIImage {
    func resizeImage(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 :(得分:9)

Swift 4.0 -

如果您正在处理包含透明胶片的图像,则接受的答案功能实际上会将透明区域转换为黑色。

如果您希望缩放并保持透明胶片的位置,请尝试以下功能:

func resizeImageWith(image: UIImage, newSize: CGSize) -> UIImage {

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

    let ratio = max(horizontalRatio, verticalRatio)
    let newSize = CGSize(width: image.size.width * ratio, height: image.size.height * ratio)
    var newImage: UIImage

    if #available(iOS 10.0, *) {
        let renderFormat = UIGraphicsImageRendererFormat.default()
        renderFormat.opaque = false
        let renderer = UIGraphicsImageRenderer(size: CGSize(width: newSize.width, height: newSize.height), format: renderFormat)
        newImage = renderer.image {
            (context) in
            image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        }
    } else {
        UIGraphicsBeginImageContextWithOptions(CGSize(width: newSize.width, height: newSize.height), isOpaque, 0)
        image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        newImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
    }

    return newImage
}

答案 5 :(得分:7)

此功能将返回您指定的宽度的图像:

func scaleImage(image: UIImage, maximumWidth: CGFloat) -> UIImage {
    let rect: CGRect = CGRectMake(0, 0, image.size.width, image.size.height)
    let cgImage: CGImageRef = CGImageCreateWithImageInRect(image.CGImage!, rect)!
    return UIImage(CGImage: cgImage, scale: image.size.width / maximumWidth, orientation: image.imageOrientation)
}

Swift 3.0

func scaledImage(_ image: UIImage, maximumWidth: CGFloat) -> UIImage {
    let rect: CGRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
    let cgImage: CGImage = image.cgImage!.cropping(to: rect)!
    return UIImage(cgImage: cgImage, scale: image.size.width / maximumWidth, orientation: image.imageOrientation)
}

答案 6 :(得分:7)

此代码使用iOS 10中引入的 UIGraphicsImageRenderer :在我的测试中,它比使用UIGraphicsBeginImageContext(Swift 4 / Xcode 9)的早期样本快10-40%:

extension UIImage {
        func renderResizedImage (newWidth: CGFloat) -> UIImage {
            let scale = newWidth / self.size.width
            let newHeight = self.size.height * scale
            let newSize = CGSize(width: newWidth, height: newHeight)

            let renderer = UIGraphicsImageRenderer(size: newSize)

            let image = renderer.image { (context) in
                self.draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: newSize))
            }
            return image
        }
    }

答案 7 :(得分:1)

func getScaledDimension(width: CGFloat, height: CGFloat,new_width: CGFloat, new_height: CGFloat)->CGPoint {

        let widthAspect =  (width / new_width)
        let heightAspect = (height / new_height)
        if widthAspect == 0 || heightAspect == 0 {
            return CGPoint(x: width, y: height)
        }
        var width1 : CGFloat = 0
        var height1 : CGFloat =  0
        if widthAspect > heightAspect {
            width1 = (width) / heightAspect
            height1 = (height) / heightAspect
        } else {
            width1 = (width) / widthAspect
            height1 = (height) / widthAspect
        }

        return CGPoint(x: width1, y: height1 )
    }



    func ResizeImage(image: UIImage, targetSize: CGSize) -> UIImage {

        let rect = CGRectMake(0, 0, targetSize.width, targetSize.height)

        UIGraphicsBeginImageContextWithOptions(targetSize, false, 1.0)
        image.drawInRect(rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage
    }


 let imagesize =  getScaledDimension(image.size.width, height: image.size.height , new_width: Width, new_height: Hieght)

        print("Image Size Scaled Dimension -> H:\(imagesize.x) W:\(imagesize.y)")

        let newImage = ResizeImage(image, targetSize: CGSizeMake(imagesize.x,imagesize.y))
        print("Resize Image Size -> H\(newImage.size.height) W\(newImage.size.width) ")

答案 8 :(得分:1)

此代码在正方形图像上效果很好,并且不会丢失质量

extension UIImage {

func resize(targetSize: CGSize) -> UIImage {
    return UIGraphicsImageRenderer(size:targetSize).image { _ in
        self.draw(in: CGRect(origin: .zero, size: targetSize))
    }
}

}

答案来自: Resize Image without losing quality

答案 9 :(得分:0)

将图像尺寸缩小1024,您始终可以根据服务器容量进行转换

func resizeImage(image: UIImage) -> UIImage {

        if image.size.height >= 1024 && image.size.width >= 1024 {

            UIGraphicsBeginImageContext(CGSize(width:1024, height:1024))
            image.draw(in: CGRect(x:0, y:0, width:1024, height:1024))

            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            return newImage!

        }
        else if image.size.height >= 1024 && image.size.width < 1024
        {

            UIGraphicsBeginImageContext(CGSize(width:image.size.width, height:1024))
            image.draw(in: CGRect(x:0, y:0, width:image.size.width, height:1024))

            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            return newImage!

        }
        else if image.size.width >= 1024 && image.size.height < 1024
        {

            UIGraphicsBeginImageContext(CGSize(width:1024, height:image.size.height))
            image.draw(in: CGRect(x:0, y:0, width:1024, height:image.size.height))

            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            return newImage!

        }
        else
        {
            return image
        }

    }

答案 10 :(得分:0)

在Swift 4.2中使用最大尺寸进一步改善 @rommex 的答案:

In [120]: s.astype('Int64')
Out[120]:
0      1
1    NaN
dtype: Int64

In [121]: type(s.astype('Int64')[0])
Out[121]: numpy.int64

In [122]: type(s.astype('Int64')[1])
Out[122]: float

答案 11 :(得分:0)

这是@Christoph R针对Swift 3.0发布的答案的延续。 该代码适用于Swift 5.0.1。

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

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

    return newImage!
}

在呼叫者站点

TaskUtilties.resizeImage(image: rawImage!, newWidth: CGFloat(50))