Pressing_Keys_24_7
Pressing_Keys_24_7

Reputation: 1863

Saved Transparent Images returns with a black background in Swift

I am using the following functions to save and retrieve images in my View controller. But, the retrieved image of a saved image, (which is a transparent .png file) returns with a black background. Would appreciate if anyone could please let me know how could I resolve this issue? Thanks for the help!

func saveImage(image: UIImage) -> Bool {
    guard let data = image.jpegData(compressionQuality: 1) ?? image.pngData() else {
        return false
    }
    guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
        return false
    }
    do {
        try data.write(to: directory.appendingPathComponent("fileName.png")!)
        return true
    } catch {
        print(error.localizedDescription)
        return false
    }
}

func getSavedImage(named: String) -> UIImage? {
    if let dir = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) {
        return UIImage(contentsOfFile: URL(fileURLWithPath: dir.absoluteString).appendingPathComponent(named).path)
    }
    return nil
}

Upvotes: 0

Views: 651

Answers (1)

YodagamaHeshan
YodagamaHeshan

Reputation: 6500

JPEG can't support transparency because it uses RGB color space. so that you can save png image without compromising.

func saveImage(image: UIImage) -> Bool {
        guard let data = image.pngData()
        guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
            return false
        }
        do {
            try data.write(to: directory.appendingPathComponent("fileName.png")!)
            return true
        } catch {
            print(error.localizedDescription)
            return false
        }
    }
    
func getSavedImage(named: String) -> UIImage? {
    if let dir = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) {
        return UIImage(contentsOfFile: URL(fileURLWithPath: dir.absoluteString).appendingPathComponent(named).path)
    }
    return nil
}

Upvotes: 3

Related Questions