Home > database >  SwiftUI - how can I resize images before uploading to Firebase Storage
SwiftUI - how can I resize images before uploading to Firebase Storage

Time:10-12

I have successfully uploaded the image to Storage, but I have a problem that when my image is large in size it will be slow in rendering to the UI. I want to resize my images to the same default size before uploading to Storage.

func uploadImageToStorage(image: UIImage) {
        if let imageData = image.jpegData(compressionQuality: 1) {
            let storage = Storage.storage()
            let storageRef = storage.reference()
            let testRef = storageRef.child("avatar/\(user.id)/avatar.png")
            testRef.putData(imageData, metadata: nil) {( _, error) in
                if let error = error {
                    print("an error has occured - \(error.localizedDescription)")
                } else {
                    print("image uploaded successfully")
                }
            }
        } else {
            print("Coldn't unwrap/case imgae to data")
        }
    }

CodePudding user response:

1. Define a function to change the image size.

How to Resize image in Swift?

func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage? {
    let size = image.size
    
    let widthRatio  = targetSize.width  / size.width
    let heightRatio = targetSize.height / 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(origin: .zero, size: newSize)
    
    UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
    image.draw(in: rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    
    return newImage
}

2. Call that function when uploading.

func uploadImageToStorage(image: UIImage) {
        if let imageData = resizeImage(image: image, targetSize: CGSize(width: 200, height: 200))?.pngData() {
            let storage = Storage.storage()
            let storageRef = storage.reference()
            let testRef = storageRef.child("avatar/\(user.id)/avatar.png")
            testRef.putData(imageData, metadata: nil) {( _, error) in
                if let error = error {
                    print("an error has occured - \(error.localizedDescription)")
                } else {
                    print("image uploaded successfully")
                }
            }
        } else {
            print("Coldn't unwrap/case imgae to data")
        }
    }
  • Related