在swift中

时间:2018-01-09 07:00:45

标签: ios swift

当我调整图像大小时,我遇到了问题。当我从图库中选择一个图像时,它压缩得如此之小,但是当我在另一个视图控制器中得到这个图像时,它显示模糊。如果增加图像大小的大小比某些图像上传但不上传。

@IBAction func imagegallery(_ sender: Any) {
    checkPermission()
    imagePicker.allowsEditing = false
    imagePicker.sourceType = .photoLibrary
    present(imagePicker, animated: true, completion: nil)   
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let select = info[UIImagePickerControllerOriginalImage] as? UIImage {

    ## resize the image ##

        DispatchQueue.main.async {

            let imaged = self.resizeImage(image: select, withSize: CGSize(width: 300 , height: 100))
            let imageData = UIImageJPEGRepresentation(imaged, 0.75)!
            self.strBase64 = (imageData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters))
            self.dismiss(animated: true, completion: nil)
        }    
    } 
}

调整大小功能

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!
}

0 个答案:

没有答案