Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVAssetImageGenerator generates an image with slightly wrong colors, but only on iOS 13.X

Tags:

swift

It seems that AVAssetImageGenerator().copyCGImage generates an image with slightly wrong colors on iOS 13.x. The colors are correct on iOS 12.4.

Have anyone else experienced this?


What it looks like

1 = AVPlayer (Correct color)

2 = AVAssetImageGenerator result

Notice how the background colors are slightly different.

enter image description here


Code

extension AVPlayer{
    var poster: UIImage? {
        guard let asset = self.currentItem?.asset else {
            return nil
        }

        let videoFrameCGImage = try! AVAssetImageGenerator(asset: asset).copyCGImage(at: CMTimeMake(value: 1, timescale: 10), actualTime: nil)

        return UIImage(cgImage: videoFrameCGImage)
    }
}
like image 988
August Bjornberg Avatar asked Jun 11 '20 00:06

August Bjornberg


1 Answers

I had the same issue when generating thumbnails, and Pranav's comment above was the hint I needed. Copying the output CGImage into device RGB colorspace does the trick for me:

generator.appliesPreferredTrackTransform = true
let thumbTime = CMTimeMakeWithSeconds(0, preferredTimescale: 30)
generator.maximumSize = maxSize ?? CGSize(width: 100, height: 100)
var cgImage = try? generator.copyCGImage(at: thumbTime, actualTime: nil)

// This was the missing line - correct the color space
cgImage = cgImage?.copy(colorSpace: CGColorSpaceCreateDeviceRGB())

if let cgImage = cgImage {
     return UIImage(cgImage: cgImage)
}

This changed the cgImage.colorSpace from using:

<CGColorSpace 0x28248f660> (kCGColorSpaceICCBased; kCGColorSpaceModelRGB; HDTV)

to using:

<CGColorSpace 0x282484120> (kCGColorSpaceDeviceRGB)
like image 88
adam.wulf Avatar answered Nov 17 '22 23:11

adam.wulf