0

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
}
Daniel Patriarca
  • 361
  • 3
  • 20
  • Hello, your image come from an `UIImagePickerController` ? – Etienne Jézéquel Jan 02 '20 at 08:15
  • No. The images are coming from amazon s3. I left off the code that extracts the image and converts it into a UIImage. – Daniel Patriarca Jan 03 '20 at 00:31
  • I haven't had time to digest, but the link below suggests the cause of this issue is that converting to PNG representation drops of the image orientation. This makes the underlying question "how to update this function in swift to ensure orientation gets re-applied". https://inneka.com/programming/objective-c/ios-png-image-rotated-90-degrees/ – Daniel Patriarca Jan 03 '20 at 00:53

0 Answers0