UIImageJPEGRepresentation | generateJPEGRepresentation saves image as nil? Swift 3

creatando picture creatando · Feb 25, 2017 · Viewed 7.1k times · Source

I am currently designing a database management application with Realm, where I have managed to create and retrieve an object successfully. The problem I am having is with updating/editing - specifically updating the UIImage that the user has uploaded. With Realm, I save the path of the image and then retrieve it by loading that path (in Documents Directory).

When the user tries to save the changed image, for some odd reason the UIImageJPEGRepresentation saves the changed image as nil, thus removing the user's image. It's strange because the initial creation of a data object stores it just fine.

I have tried to check whether the image is being passed correctly with some debugging, and have found that it does so just fine and the right path is being saved on.

Here is my update method:

func  updateImage() { 
    let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    let fileURL = documentsDirectoryURL.appendingPathComponent("\(selectedPicPath!)")

    if FileManager.default.fileExists(atPath: fileURL.path) {
        do {
            if profilePic.image != nil {
            let image = profilePic.image!.generateJPEGRepresentation()
            try! image.write(to: fileURL, options: .atomicWrite)
            }
        } catch {
            print(error)
        }
    } else {
            print("Image Not Added")
    }
}

Can anyone see any problems?

Answer

user7587085 picture user7587085 · Feb 25, 2017
let image = profilePic.image!.generateJPEGRepresentation()

Check this line, whether it is returning nil value or data? If nil, then use following code to test your image store, it's working. Also ensure your actual image has JPEG file format extension, that you are trying to generate.

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

// For PNG Image

if let image = UIImage(named: "example.png") {
    if let data = UIImagePNGRepresentation() {
        let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
        try? data.write(to: filename)
    }
}

For JPG image

if let image = UIImage(named: "example.jpg") {
    if let data = UIImageJPEGRepresentation(image, 1.0) {
        let filename = getDocumentsDirectory().appendingPathComponent("copy.jpg")
        try? data.write(to: filename)
    }
}