Skip to content

Instantly share code, notes, and snippets.

let imageDecoder = DBImageDecoder()
var imageData = Data()
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
imageData.append(data)
imageDecoder.setData(imageData, allDataReceived: false)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
let task = urlSession.dataTask(with: url) { data, _, _ in
guard let data = data else {
return
}
let imageDecoder = DBImageDecoder()
imageDecoder.setData(data, allDataReceived: true)
guard let uiImage = imageDecoder.uiImage else {
return
//
// DBImageDecoder.swift
// Test
//
// Created by Varun Tomar on 03/08/21.
//
import ImageIO
import Foundation
//
// DBImageDecoder+UIKit.swift
// Test
//
// Created by Varun Tomar on 04/08/21.
//
import UIKit
extension DBImageDecoder {
func isFrameComplete(at index: Int) -> Bool {
assert(frameCount > index)
if index == frameCount - 1 {
return CGImageSourceGetStatus(imageSource) == .statusComplete
}
return CGImageSourceGetStatusAtIndex(imageSource, index) == .statusComplete
}
func createFrameImage(at index: Int, downsamplingLevel: DownSamplingLevel = .default, decodingOptions: DecodingOptions = .default) -> CGImage? {
guard index < frameCount else {
return nil
}
let image: CGImage?
let options: CFDictionary
switch decodingOptions.mode {
struct DecodingOptions {
enum Mode {
case synchronous
case asynchronous
}
static var `default`: DecodingOptions {
DecodingOptions(mode: .asynchronous, sizeForDrawing: nil)
}
enum DownSamplingLevel: Int {
case level0 = 1
case level1 = 2
case level2 = 4
case level3 = 8
public static var `default`: DownSamplingLevel {
.level0
}
}
private static let imageSourceOptions: [CFString: Any] = [
kCGImageSourceShouldCache: true
]
private static let imageSourceAsyncOptions: [CFString: Any] = [
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceCreateThumbnailFromImageAlways: true
]
func frameSize(at index: Int, downsamplingLevel: DownSamplingLevel = .default) -> CGSize? {
guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, index, imageSourceOptions(with: downsamplingLevel)) as? [CFString: Any] else {
return nil
}
guard let width = properties[kCGImagePropertyPixelWidth] as? Int, let height = properties[kCGImagePropertyPixelHeight] as? Int else {
return nil
}
return CGSize(width: width, height: height)