another.im-ios/ConversationsClassic/AppCore/Files/FileProcessing.swift
2024-07-14 11:04:40 +02:00

68 lines
2.5 KiB
Swift

import Foundation
import UIKit
final class FileProcessing {
static let shared = FileProcessing()
static var fileFolder: URL {
// swiftlint:disable:next force_unwrapping
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let subdirectoryURL = documentsURL.appendingPathComponent(Const.fileFolder)
if !FileManager.default.fileExists(atPath: subdirectoryURL.path) {
try? FileManager.default.createDirectory(at: subdirectoryURL, withIntermediateDirectories: true, attributes: nil)
}
return subdirectoryURL
}
func createThumbnail(localUrl: URL) -> URL? {
let fileExtension = localUrl.pathExtension
let fileNameWithoutExtension = localUrl.deletingPathExtension().lastPathComponent
let thumbnailFileName = fileNameWithoutExtension + "_thumb." + fileExtension
let thumbnailUrl = FileProcessing.fileFolder.appendingPathComponent(thumbnailFileName)
// check if thumbnail already exists
if FileManager.default.fileExists(atPath: thumbnailUrl.path) {
return thumbnailUrl
}
// create thumbnail if not exists
switch localUrl.lastPathComponent.attachmentType {
case .image:
guard let image = UIImage(contentsOfFile: localUrl.path) else { return nil }
let targetSize = CGSize(width: Const.attachmentPreviewSize, height: Const.attachmentPreviewSize)
guard let thumbnail = scaleAndCropImage(image, targetSize) else { return nil }
guard let data = thumbnail.pngData() else { return nil }
do {
try data.write(to: thumbnailUrl)
return thumbnailUrl
} catch {
return nil
}
default:
return nil
}
}
}
func scaleAndCropImage(_ img: UIImage, _ size: CGSize) -> UIImage? {
let aspect = img.size.width / img.size.height
let targetAspect = size.width / size.height
var newWidth: CGFloat
var newHeight: CGFloat
if aspect < targetAspect {
newWidth = size.width
newHeight = size.width / aspect
} else {
newHeight = size.height
newWidth = size.height * aspect
}
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
img.draw(in: CGRect(x: (size.width - newWidth) / 2, y: (size.height - newHeight) / 2, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}