util: add ImageResizer to change size of images

This commit is contained in:
Suhail Saqan
2023-09-19 13:24:11 -07:00
committed by William Casarin
parent 41e036cff2
commit cdacbcfdca
2 changed files with 52 additions and 0 deletions

View File

@@ -0,0 +1,40 @@
//
// ImageResizer.swift
// damus
//
// Created by Suhail Saqan on 8/5/23.
//
import Foundation
import UIKit
public enum ImageResizingError: Error {
case cannotRetrieveFromURL
case cannotRetrieveFromData
}
public struct ImageResizer {
public var targetWidth: CGFloat
public init(targetWidth: CGFloat) {
self.targetWidth = targetWidth
}
public func resize(at url: URL) -> UIImage? {
guard let image = UIImage(contentsOfFile: url.path) else {
return nil
}
return self.resize(image: image)
}
public func resize(image: UIImage) -> UIImage {
let originalSize = image.size
let targetSize = CGSize(width: targetWidth, height: targetWidth*originalSize.height/originalSize.width)
let renderer = UIGraphicsImageRenderer(size: targetSize)
return renderer.image { (context) in
image.draw(in: CGRect(origin: .zero, size: targetSize))
}
}
}