Thegasman2000
Thegasman2000

Reputation: 115

Swift 3.0 writing Image to Directory

I have a simple ImagePicker for the user to select, or take, a profile picture. I want to save this image to the Home Directory for easy loading later.

The problem is with the Image type not being set.

    //Save Image
    _ = PPimagePicked.image
    let imageData = UIImageJPEGRepresentation(PPimagePicked.image!, 0.6)
    let compressedJPGImage = UIImage(data: imageData!)
    UIImageWriteToSavedPhotosAlbum(compressedJPGImage!, nil, nil, nil)
    // Get Document Root Path
    let path = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/profile.jpg")
    do {
        //Save image to Root
        try imageData?.write(to: path, options:  .atomic)
        print("Saved To Root")
    } catch let error {
        print(error)
    }

The exact Error is :

"[Generic] Creating an image format with an unknown type is an error"

Upvotes: 3

Views: 6917

Answers (2)

neprocker
neprocker

Reputation: 170

try converting the image to image data

       let imageCapture = UIImage(data: dataImage)!
        UIImageWriteToSavedPhotosAlbum((image: imageCapture), nil, nil, nil)

Upvotes: 1

Parth Adroja
Parth Adroja

Reputation: 13514

Please try this code i am using it in swift 2.2. Below method includes for both UIImageJPEGRepresentation, UIImagePNGRepresentation

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

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

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

Upvotes: 2

Related Questions