Skip to content

Instantly share code, notes, and snippets.

@winstondu
Created June 30, 2021 21:40
Show Gist options
  • Save winstondu/39305dc13c960ab335c0ce7f6756e216 to your computer and use it in GitHub Desktop.
Save winstondu/39305dc13c960ab335c0ce7f6756e216 to your computer and use it in GitHub Desktop.
SDWebImageManager: Store image with transform
//
// SDWebImageManager.swift
// Backbone
//
// Created by Winston Du on 1/8/20.
//
import Foundation
import SDWebImage
extension SDWebImageManager {
// Largely a transpilation of relevant portion of SDWebImageManager.callTransformProcessForOperation
func storeWithTransform(image: UIImage?, imageData: Data?, url: URL?, forKey key: String, transformer: SDImageTransformer, cacheType: SDImageCacheType = SDImageCacheType.all, cacheSerializer: SDWebImageCacheSerializer? = nil, completion: SDWebImageNoParamsBlock?) {
if let image = image, let transformedImage =
transformer.transformedImage(with: image, forKey: key) {
let transformerKey: String = transformer.transformerKey;
let cacheKey: String? = SDTransformedKeyForKey(key, transformerKey)
let imageWasTransformed: Bool = transformedImage != image
var cacheData: Data?;
// pass nil if the image was transformed, so we can recalculate the data from the image
if cacheSerializer != nil && (cacheType == .disk || cacheType == .all) {
cacheData = cacheSerializer?.cacheData(with: transformedImage, originalData: imageWasTransformed ? nil : imageData, imageURL: url)
} else {
cacheData = (imageWasTransformed ? nil : imageData);
}
// keep the original image format and extended data
// Image Metadata
transformedImage.sd_isIncremental = image.sd_isIncremental;
transformedImage.sd_imageLoopCount = image.sd_imageLoopCount;
transformedImage.sd_imageFormat = image.sd_imageFormat;
// Force Decode
transformedImage.sd_isDecoded = image.sd_isDecoded;
// Extended Cache Data
transformedImage.sd_extendedObject = image.sd_extendedObject;
self.imageCache.store(image, imageData: cacheData, forKey: cacheKey, cacheType: cacheType, completion: completion)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment