Home>

I'm developing an application with swift, saving png images with UserDefaults and displaying them on multiple screens
When creating an image, I want to reflect it because it is made transparent

Error message
I can display it on the screen, but when I read it, the background becomes white without being transparent
Applicable source code
Save
UserDefaults.standard.set (selectedImage! .JpegData (compressionQuality: 1.0), forKey: "imageData")
Read
let imageDate: NSData = UserDefaults.standard.object (forKey: "imageData") as! NSData
        selectedFriends.image = UIImage (data: imageDate as Data)

If i put the image in the imageview as it is, the background is transparent, so there is no problem with the image itself

Supplemental information (FW/tool version etc.)

Swift version is 5

  • Answer # 1

    selectedImage! .jpegData (compressionQuality: 1.0)


    Isn't it a problem to extract NSData in JPEG format?
    What happens if I extract it in PNG format using pngData ()?

  • Answer # 2

    JPEG format does not have the concept of transparency.
    Even if the image is transparent, the transparency information will be lost when converted to JPEG.

    And

    let imageDate: NSData = UserDefaults.standard.object (forKey: "imageData") as! NSData


    However,nilis returned when there is nothing in UserDefaults at the first startup.
    Be careful as force cast can fail.