Skip to content

Instantly share code, notes, and snippets.

@awxkee
Created October 17, 2023 03:54
Show Gist options
  • Select an option

  • Save awxkee/fb5380ff7588494cf39728f29f78622b to your computer and use it in GitHub Desktop.

Select an option

Save awxkee/fb5380ff7588494cf39728f29f78622b to your computer and use it in GitHub Desktop.
Animated AVIF SDWebImage
import avifc
public class SDWebImageAVIFAnimatedCoder: NSObject, SDAnimatedImageCoder {
private let decoder: AVIFAnimatedDecoder
public required init?(animatedImageData data: Data?, options: [SDImageCoderOption : Any]? = nil) {
guard let data, let mDecoder = AVIFAnimatedDecoder(data: data) else {
return nil
}
decoder = mDecoder
super.init()
}
public func canDecode(from data: Data?) -> Bool {
guard let data else {
return false
}
return AVIFDecoder().isAVIF(data: data)
}
public func decodedImage(with data: Data?, options: [SDImageCoderOption : Any]? = nil) -> AVIFSDImage? {
guard let data else {
return nil
}
return AVIFDecoder.decode(data)
}
public func canEncode(to format: SDImageFormat) -> Bool {
return true
}
public func encodedData(with image: AVIFSDImage?, format: SDImageFormat, options: [SDImageCoderOption : Any]? = nil) -> Data? {
guard let image else {
return nil
}
return try? AVIFEncoder.encode(image: image, quality: 50)
}
public var animatedImageData: Data? {
nil
}
public var animatedImageFrameCount: UInt {
UInt(decoder.framesCount())
}
public var animatedImageLoopCount: UInt {
UInt.max
}
public func animatedImageFrame(at index: UInt) -> AVIFSDImage? {
return decoder.getImage(Int32(index))
}
public func animatedImageDuration(at index: UInt) -> TimeInterval {
TimeInterval(decoder.frameDuration(Int32(index)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment