conversations-classic-ios/ConversationsClassic/AppCore/Files/FileProcessing.swift

67 lines
2.4 KiB
Swift
Raw Normal View History

2024-07-13 01:29:46 +00:00
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!
2024-07-14 08:52:15 +00:00
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
2024-07-13 01:29:46 +00:00
}
2024-07-14 10:08:51 +00:00
func createThumbnail(localName: String) -> String? {
let thumbnailFileName = "thumb_\(localName)"
2024-07-14 08:52:15 +00:00
let thumbnailUrl = FileProcessing.fileFolder.appendingPathComponent(thumbnailFileName)
2024-07-14 10:08:51 +00:00
let localUrl = FileProcessing.fileFolder.appendingPathComponent(localName)
2024-07-13 01:29:46 +00:00
// check if thumbnail already exists
if FileManager.default.fileExists(atPath: thumbnailUrl.path) {
2024-07-14 10:08:51 +00:00
return thumbnailFileName
2024-07-13 01:29:46 +00:00
}
// create thumbnail if not exists
2024-07-14 10:08:51 +00:00
switch localName.attachmentType {
2024-07-13 01:29:46 +00:00
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)
2024-07-14 10:08:51 +00:00
return thumbnailFileName
2024-07-13 01:29:46 +00:00
} catch {
return nil
}
default:
return nil
}
}
}
2024-07-13 16:37:26 +00:00
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
}
2024-07-13 01:29:46 +00:00
2024-07-13 16:37:26 +00:00
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()
2024-07-13 01:29:46 +00:00
2024-07-13 16:37:26 +00:00
return newImage
2024-07-13 01:29:46 +00:00
}