huynguyencong / DataCache

Simple disk and memory cache for iOS
MIT License
101 stars 20 forks source link

Cached images removes Mask #6

Closed otymartin closed 8 years ago

otymartin commented 8 years ago

@huynguyencong Im using this library to cache stickers for iMessage Extension Sticker App My images are png's with circle masks around them.

When i download and display them fresh from my database, the masks remain. But when I load from cache, there is no longer a mask. Its a square image with a white background.

How can I fix this?

// HERE I CACHE IMAGE FROM THE URL
 if let image: UIImage = imageFromURL(url: url!) {
                        DataCache.instance.write(image: image, forKey: sticker.downloadURL)
                    }

// HERE I RETRIEVE THE IMAGE FROM CACHE
if let cachedImage = DataCache.instance.readImageForKey(key: sticker.downloadURL)  {
                sticker.localURL = imageToURL(stickerName: sticker.name, image: cachedImage)
                self.createSticker(sticker: sticker)
                re

//HERE ONCE I GET IMAGE FROM URL, I STORE IT IN TEMP FOLDER
public func imageToURL(stickerName: String, image: UIImage) -> URL {

    let url: URL = tempFilePath(stickerName: stickerName)
    let imageData = UIImagePNGRepresentation(image)

    do {
        try imageData?.write(to: url)
    } catch {
        print(error)
    }
    return url
}

//HERE I TURN URL to UIIMAGE
public func imageFromURL(url: URL) -> UIImage {
    var data: Data? = nil
    do {
        try data = Data(contentsOf: url)
    } catch {
        print(error)
    }

    return UIImage(data: data!)!
}
huynguyencong commented 8 years ago

What is your image type (PNG, JPEG, GIF, ...)? Now DataCache just support PNG and JPEG.

huynguyencong commented 8 years ago

If it is PNG file, please user param format when you write image DataCache.instance.write(image: image, forKey: sticker.downloadURL, format: .png)

otymartin commented 8 years ago

@huynguyencong Thanks I actually just figured it out and was about to document my solution.

But yes it was a PNG format. By default if no format is specified, I noticed you cache the image as a JPG which will strip out any PNG attributes such as masks.

Thanks :)

huynguyencong commented 8 years ago

You're welcome :)