在上传到swift 3中的Firebase存储之前调整UIImage的大小

时间:2017-05-19 21:06:40

标签: ios swift firebase uiimage storage

我已经设置了我的应用程序,以便当我按下“cambiaimmagineutente”按钮时出现一个选择器控制器,我可以选择我使用“UIImagePickerControllerReferenceURL”上传到FIRStorage的图像。我无法找到一种方法来调整图像大小,然后再上传它以节省空间并将其放在较小的图像视图中。 这是代码:

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

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    picker.dismiss(animated: true, completion:nil)


    // if it's a photo from the library, not an image from the camera
    if #available(iOS 8.0, *), let referenceUrl = info[UIImagePickerControllerReferenceURL] as? URL {
        let assets = PHAsset.fetchAssets(withALAssetURLs: [referenceUrl], options: nil)
        let asset = assets.firstObject
        asset?.requestContentEditingInput(with: nil, completionHandler: { (contentEditingInput, info) in
            let imageFile = contentEditingInput?.fullSizeImageURL
            let filePath = FIRAuth.auth()!.currentUser!.uid +
            "/\(Int(Date.timeIntervalSinceReferenceDate * 1000))/\(imageFile!.lastPathComponent)"
            // [START uploadimage]
            self.storageRef.child(filePath)
                .putFile(imageFile!, metadata: nil) { (metadata, error) in
                    if let error = error {
                        //an error occured
                        print("Error uploading: \(error)")
                        return
                    }
                    self.uploadSuccess(metadata!, storagePath: filePath)
            }
            // [END uploadimage]
        })
    } else {
        guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else { return }
        guard let imageData = UIImageJPEGRepresentation(image, 0.8) else { return }
        let imagePath = FIRAuth.auth()!.currentUser!.uid +
        "/\(Int(Date.timeIntervalSinceReferenceDate * 1000)).jpg"
        let metadata = FIRStorageMetadata()
        metadata.contentType = "image/jpeg"
        self.storageRef.child(imagePath)
            .put(imageData, metadata: metadata) { (metadata, error) in
                if let error = error {
                    //an error occured
                    print("Error uploading: \(error)")

                    return
                }
                self.uploadSuccess(metadata!, storagePath: imagePath)
        }
    }
}

func uploadSuccess(_ metadata: FIRStorageMetadata, storagePath: String) {
    print("Upload Succeeded!")
    //self.urlTextView.text = metadata.downloadURL()?.absoluteString
    UserDefaults.standard.set(storagePath, forKey: "storagePath")
    UserDefaults.standard.synchronize()
    //self.downloadPicButton.isEnabled = true
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    picker.dismiss(animated: true, completion:nil)
}

1 个答案:

答案 0 :(得分:1)

您可以使用:

 func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
        let size = image.size

        let widthRatio  = targetSize.width  / image.size.width
        let heightRatio = targetSize.height / image.size.height

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

        let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

        UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
        image.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage!
    }

使用:

let resizedImage = resizeImage(image: selectedImage, targetSize: CGSize.init(width: 300, height: 300))

确保您还在存储规则中将写入规则设为最大值!