upscale an image using scale2x in swift

To upscale an image using scale2x in Swift, you can use the following code:

main.swift
func scale2x(image: UIImage) -> UIImage? {
    guard let cgImage = image.cgImage else { return nil }
    
    let width = cgImage.width * 2
    let height = cgImage.height * 2
    let bytesPerPixel = 4
    let bytesPerRow = bytesPerPixel * width
    let bitmapInfo = cgImage.bitmapInfo.rawValue
    
    let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: bytesPerRow, space: cgImage.colorSpace!, bitmapInfo: bitmapInfo)!
    
    context.interpolationQuality = .none
    context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width/2, height: height/2))
    
    var scaledImage = context.makeImage().flatMap { UIImage(cgImage: $0) }
    
    // Repeat the scaling process to get a better scale
    for _ in 0..<1 {
        guard let cgImage = scaledImage?.cgImage else { return nil }
        
        let width = cgImage.width * 2
        let height = cgImage.height * 2
        let bytesPerPixel = 4
        let bytesPerRow = bytesPerPixel * width
        let bitmapInfo = cgImage.bitmapInfo.rawValue
        
        let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: bytesPerRow, space: cgImage.colorSpace!, bitmapInfo: bitmapInfo)!
        
        context.interpolationQuality = .none
        context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width/2, height: height/2))
        
        scaledImage = context.makeImage().flatMap { UIImage(cgImage: $0) }
    }
    
    return scaledImage
}
1538 chars
37 lines

This function takes an input UIImage and returns an upscaled UIImage. The context objects are created with desired resolution and scale2x algorithm is executed twice to increase the resolution of the input image by a factor of 4. By repeating the process, the algorithm is able to smooth out the pixels and reduce blockiness.

gistlibby LogSnag