I have an app where I want to create thumbnails from existing UIImages. I used the function below to take the argument of the full size UIImage and return the 100pxl icon/thumb UIImage. It all seemed to be working great but I noticed that some of the resulting icon/thumb UIImages were rotated 90 degrees compared to the original. Is there a problem in the code below I am not seeing that is causing certain images to rotate but not others? Perhaps a better solution for creating thumbs from UIImages?
func returnThumbnail(bigImage: UIImage) -> UIImage {
var thumbnail = UIImage()
if let imageData = UIImagePNGRepresentation(bigImage){
let options = [
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceThumbnailMaxPixelSize: 100] as CFDictionary // Specify your desired size at kCGImageSourceThumbnailMaxPixelSize. 100 seems standard
imageData.withUnsafeBytes { ptr in
guard let bytes = ptr.baseAddress?.assumingMemoryBound(to: UInt8.self) else {
return
}
if let cfData = CFDataCreate(kCFAllocatorDefault, bytes, imageData.count){
let source = CGImageSourceCreateWithData(cfData, nil)!
let imageReference = CGImageSourceCreateThumbnailAtIndex(source, 0, options)!
thumbnail = UIImage(cgImage: imageReference) // You get your thumbail here
}
}
}
return thumbnail
}