NCUtility+Image.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. //
  2. // NCUtility+Image.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 06/11/23.
  6. // Copyright © 2023 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import UIKit
  24. import NextcloudKit
  25. import PDFKit
  26. import Accelerate
  27. import CoreMedia
  28. import Photos
  29. import SVGKit
  30. extension NCUtility {
  31. func loadImage(named imageName: String, colors: [UIColor]? = nil, size: CGFloat? = nil, useTypeIconFile: Bool = false ) -> UIImage {
  32. var image: UIImage?
  33. if useTypeIconFile {
  34. switch imageName {
  35. case NKCommon.TypeIconFile.audio.rawValue: image = UIImage(systemName: "waveform", withConfiguration: UIImage.SymbolConfiguration(weight: .thin))?.applyingSymbolConfiguration(UIImage.SymbolConfiguration(paletteColors: [NCBrandColor.shared.iconImageColor2]))
  36. case NKCommon.TypeIconFile.code.rawValue: image = UIImage(systemName: "ellipsis.curlybraces", withConfiguration: UIImage.SymbolConfiguration(weight: .thin))?.applyingSymbolConfiguration(UIImage.SymbolConfiguration(paletteColors: [NCBrandColor.shared.iconImageColor2]))
  37. case NKCommon.TypeIconFile.compress.rawValue: image = UIImage(systemName: "doc.zipper", withConfiguration: UIImage.SymbolConfiguration(weight: .thin))?.applyingSymbolConfiguration(UIImage.SymbolConfiguration(paletteColors: [NCBrandColor.shared.iconImageColor2]))
  38. case NKCommon.TypeIconFile.directory.rawValue: image = UIImage(named: "folder")! .image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width / 2)
  39. case NKCommon.TypeIconFile.document.rawValue: image = UIImage(systemName: "doc.richtext", withConfiguration: UIImage.SymbolConfiguration(weight: .thin))?.applyingSymbolConfiguration(UIImage.SymbolConfiguration(paletteColors: [NCBrandColor.shared.documentIconColor]))
  40. case NKCommon.TypeIconFile.image.rawValue: image = UIImage(systemName: "photo", withConfiguration: UIImage.SymbolConfiguration(weight: .thin))?.applyingSymbolConfiguration(UIImage.SymbolConfiguration(paletteColors: [NCBrandColor.shared.iconImageColor2]))
  41. case NKCommon.TypeIconFile.movie.rawValue: image = UIImage(systemName: "video", withConfiguration: UIImage.SymbolConfiguration(weight: .thin))?.applyingSymbolConfiguration(UIImage.SymbolConfiguration(paletteColors: [NCBrandColor.shared.iconImageColor2]))
  42. case NKCommon.TypeIconFile.pdf.rawValue: image = UIImage(named: "file_pdf")!
  43. case NKCommon.TypeIconFile.ppt.rawValue: image = UIImage(systemName: "play.rectangle", withConfiguration: UIImage.SymbolConfiguration(weight: .thin))?.applyingSymbolConfiguration(UIImage.SymbolConfiguration(paletteColors: [NCBrandColor.shared.presentationIconColor]))
  44. case NKCommon.TypeIconFile.txt.rawValue: image = UIImage(systemName: "doc.text", withConfiguration: UIImage.SymbolConfiguration(weight: .thin))?.applyingSymbolConfiguration(UIImage.SymbolConfiguration(paletteColors: [NCBrandColor.shared.iconImageColor2]))
  45. case NKCommon.TypeIconFile.url.rawValue: image = UIImage(systemName: "network", withConfiguration: UIImage.SymbolConfiguration(weight: .thin))?.applyingSymbolConfiguration(UIImage.SymbolConfiguration(paletteColors: [NCBrandColor.shared.iconImageColor2]))
  46. case NKCommon.TypeIconFile.xls.rawValue: image = UIImage(systemName: "tablecells", withConfiguration: UIImage.SymbolConfiguration(weight: .thin))?.applyingSymbolConfiguration(UIImage.SymbolConfiguration(paletteColors: [NCBrandColor.shared.spreadsheetIconColor]))
  47. default: image = UIImage(systemName: "doc", withConfiguration: UIImage.SymbolConfiguration(weight: .thin))?.applyingSymbolConfiguration(UIImage.SymbolConfiguration(paletteColors: [NCBrandColor.shared.iconImageColor2]))
  48. }
  49. }
  50. if let image { return image }
  51. // SF IMAGE
  52. if let colors {
  53. image = UIImage(systemName: imageName, withConfiguration: UIImage.SymbolConfiguration(weight: .light))?.applyingSymbolConfiguration(UIImage.SymbolConfiguration(paletteColors: colors))
  54. } else {
  55. image = UIImage(systemName: imageName, withConfiguration: UIImage.SymbolConfiguration(weight: .light))
  56. }
  57. if let image { return image }
  58. // IMAGES
  59. if let color = colors?.first, let size {
  60. image = UIImage(named: imageName)?.image(color: color, size: size)
  61. } else if let color = colors?.first, size == nil {
  62. image = UIImage(named: imageName)?.image(color: color, size: 50)
  63. } else if colors == nil, size == nil {
  64. image = UIImage(named: imageName)?.resizeImage(size: CGSize(width: 50, height: 50))
  65. } else if colors == nil, let size {
  66. image = UIImage(named: imageName)?.resizeImage(size: CGSize(width: size, height: size))
  67. }
  68. if let image { return image }
  69. // NO IMAGES FOUND
  70. if let color = colors?.first, let size {
  71. return UIImage(systemName: "doc")!.image(color: color, size: size)
  72. } else {
  73. return UIImage(systemName: "doc")!
  74. }
  75. }
  76. func loadUserImage(for user: String, displayName: String?, userBaseUrl: NCUserBaseUrl) -> UIImage {
  77. let fileName = userBaseUrl.userBaseUrl + "-" + user + ".png"
  78. let localFilePath = utilityFileSystem.directoryUserData + "/" + fileName
  79. if var localImage = UIImage(contentsOfFile: localFilePath) {
  80. let rect = CGRect(x: 0, y: 0, width: 30, height: 30)
  81. UIGraphicsBeginImageContextWithOptions(rect.size, false, 3.0)
  82. UIBezierPath(roundedRect: rect, cornerRadius: rect.size.height).addClip()
  83. localImage.draw(in: rect)
  84. localImage = UIGraphicsGetImageFromCurrentImageContext() ?? localImage
  85. UIGraphicsEndImageContext()
  86. return localImage
  87. } else if let loadedAvatar = NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName) {
  88. return loadedAvatar
  89. } else if let displayName = displayName, !displayName.isEmpty, let avatarImg = createAvatar(displayName: displayName, size: 30) {
  90. return avatarImg
  91. } else {
  92. return loadImage(named: "person.crop.circle", colors: [NCBrandColor.shared.iconImageColor])
  93. }
  94. }
  95. func imageFromVideo(url: URL, at time: TimeInterval) -> UIImage? {
  96. let asset = AVURLAsset(url: url)
  97. let assetIG = AVAssetImageGenerator(asset: asset)
  98. assetIG.appliesPreferredTrackTransform = true
  99. assetIG.apertureMode = AVAssetImageGenerator.ApertureMode.encodedPixels
  100. let cmTime = CMTime(seconds: time, preferredTimescale: 60)
  101. let thumbnailImageRef: CGImage
  102. do {
  103. thumbnailImageRef = try assetIG.copyCGImage(at: cmTime, actualTime: nil)
  104. } catch let error {
  105. print("Error: \(error)")
  106. return nil
  107. }
  108. return UIImage(cgImage: thumbnailImageRef)
  109. }
  110. func createImageFrom(fileNameView: String, ocId: String, etag: String, classFile: String) {
  111. var originalImage, scaleImagePreview, scaleImageIcon: UIImage?
  112. let fileNamePath = utilityFileSystem.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)
  113. let fileNamePathPreview = utilityFileSystem.getDirectoryProviderStoragePreviewOcId(ocId, etag: etag)
  114. let fileNamePathIcon = utilityFileSystem.getDirectoryProviderStorageIconOcId(ocId, etag: etag)
  115. if utilityFileSystem.fileProviderStorageSize(ocId, fileNameView: fileNameView) > 0 && FileManager().fileExists(atPath: fileNamePathPreview) && FileManager().fileExists(atPath: fileNamePathIcon) { return }
  116. if classFile != NKCommon.TypeClassFile.image.rawValue && classFile != NKCommon.TypeClassFile.video.rawValue { return }
  117. if classFile == NKCommon.TypeClassFile.image.rawValue {
  118. originalImage = UIImage(contentsOfFile: fileNamePath)
  119. scaleImagePreview = originalImage?.resizeImage(size: CGSize(width: NCGlobal.shared.sizePreview, height: NCGlobal.shared.sizePreview))
  120. scaleImageIcon = originalImage?.resizeImage(size: CGSize(width: NCGlobal.shared.sizeIcon, height: NCGlobal.shared.sizeIcon))
  121. try? scaleImagePreview?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathPreview))
  122. try? scaleImageIcon?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathIcon))
  123. } else if classFile == NKCommon.TypeClassFile.video.rawValue {
  124. let videoPath = NSTemporaryDirectory() + "tempvideo.mp4"
  125. utilityFileSystem.linkItem(atPath: fileNamePath, toPath: videoPath)
  126. originalImage = imageFromVideo(url: URL(fileURLWithPath: videoPath), at: 0)
  127. try? originalImage?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathPreview))
  128. try? originalImage?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathIcon))
  129. }
  130. }
  131. func getImageMetadata(_ metadata: tableMetadata, for size: CGFloat) -> UIImage? {
  132. if let image = getImage(metadata: metadata) { return image }
  133. if metadata.isVideo && !metadata.hasPreview {
  134. createImageFrom(fileNameView: metadata.fileNameView, ocId: metadata.ocId, etag: metadata.etag, classFile: metadata.classFile)
  135. }
  136. if utilityFileSystem.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag) {
  137. return UIImage(contentsOfFile: utilityFileSystem.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag))
  138. }
  139. if metadata.isVideo {
  140. return loadImage(named: "video", colors: [NCBrandColor.shared.iconImageColor2])
  141. } else if metadata.isAudio {
  142. return loadImage(named: "waveform", colors: [NCBrandColor.shared.iconImageColor2])
  143. } else {
  144. return loadImage(named: "photo", colors: [NCBrandColor.shared.iconImageColor2])
  145. }
  146. }
  147. func getImage(metadata: tableMetadata) -> UIImage? {
  148. let ext = (metadata.fileNameView as NSString).pathExtension.uppercased()
  149. var image: UIImage?
  150. if utilityFileSystem.fileProviderStorageExists(metadata) && metadata.isImage {
  151. let previewPath = utilityFileSystem.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)
  152. let iconPath = utilityFileSystem.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)
  153. let imagePath = utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  154. if ext == "GIF" {
  155. if !FileManager().fileExists(atPath: previewPath) {
  156. createImageFrom(fileNameView: metadata.fileNameView, ocId: metadata.ocId, etag: metadata.etag, classFile: metadata.classFile)
  157. }
  158. image = UIImage.animatedImage(withAnimatedGIFURL: URL(fileURLWithPath: imagePath))
  159. } else if ext == "SVG" {
  160. if let svgImage = SVGKImage(contentsOfFile: imagePath) {
  161. svgImage.size = CGSize(width: NCGlobal.shared.sizePreview, height: NCGlobal.shared.sizePreview)
  162. if let image = svgImage.uiImage {
  163. if !FileManager().fileExists(atPath: previewPath) {
  164. do {
  165. try image.pngData()?.write(to: URL(fileURLWithPath: previewPath), options: .atomic)
  166. try image.pngData()?.write(to: URL(fileURLWithPath: iconPath), options: .atomic)
  167. } catch { }
  168. }
  169. return image
  170. } else {
  171. return nil
  172. }
  173. } else {
  174. return nil
  175. }
  176. } else {
  177. createImageFrom(fileNameView: metadata.fileNameView, ocId: metadata.ocId, etag: metadata.etag, classFile: metadata.classFile)
  178. image = UIImage(contentsOfFile: imagePath)
  179. }
  180. }
  181. return image
  182. }
  183. func imageFromVideo(url: URL, at time: TimeInterval, completion: @escaping (UIImage?) -> Void) {
  184. DispatchQueue.global(qos: .userInteractive).async {
  185. let asset = AVURLAsset(url: url)
  186. let assetIG = AVAssetImageGenerator(asset: asset)
  187. assetIG.appliesPreferredTrackTransform = true
  188. assetIG.apertureMode = AVAssetImageGenerator.ApertureMode.encodedPixels
  189. let cmTime = CMTime(seconds: time, preferredTimescale: 60)
  190. let thumbnailImageRef: CGImage
  191. do {
  192. thumbnailImageRef = try assetIG.copyCGImage(at: cmTime, actualTime: nil)
  193. } catch let error {
  194. print("Error: \(error)")
  195. return completion(nil)
  196. }
  197. DispatchQueue.main.async {
  198. completion(UIImage(cgImage: thumbnailImageRef))
  199. }
  200. }
  201. }
  202. func getIcon(metadata: tableMetadata) -> UIImage? {
  203. let iconPath = self.utilityFileSystem.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)
  204. guard let icon = UIImage(contentsOfFile: iconPath) else { return nil }
  205. if Int(icon.size.width) > NCGlobal.shared.sizeIcon, Int(icon.size.height) > NCGlobal.shared.sizeIcon,
  206. let iconResize = icon.resizeImage(size: CGSize(width: NCGlobal.shared.sizeIcon, height: NCGlobal.shared.sizeIcon)) {
  207. do {
  208. if let data = iconResize.jpegData(compressionQuality: 0.5) {
  209. try data.write(to: URL(fileURLWithPath: iconPath), options: .atomic)
  210. }
  211. } catch { }
  212. return iconResize
  213. }
  214. return icon
  215. }
  216. func pdfThumbnail(url: URL, width: CGFloat = 240) -> UIImage? {
  217. guard let data = try? Data(contentsOf: url), let page = PDFDocument(data: data)?.page(at: 0) else {
  218. return nil
  219. }
  220. let pageSize = page.bounds(for: .mediaBox)
  221. let pdfScale = width / pageSize.width
  222. // Apply if you're displaying the thumbnail on screen
  223. let scale = UIScreen.main.scale * pdfScale
  224. let screenSize = CGSize(width: pageSize.width * scale, height: pageSize.height * scale)
  225. return page.thumbnail(of: screenSize, for: .mediaBox)
  226. }
  227. func createAvatar(displayName: String, size: CGFloat) -> UIImage? {
  228. guard let initials = displayName.uppercaseInitials else {
  229. return nil
  230. }
  231. let userColor = NCGlobal.shared.usernameToColor(displayName)
  232. let rect = CGRect(x: 0, y: 0, width: size, height: size)
  233. var avatarImage: UIImage?
  234. UIGraphicsBeginImageContextWithOptions(rect.size, false, 3.0)
  235. let context = UIGraphicsGetCurrentContext()
  236. UIBezierPath(roundedRect: rect, cornerRadius: rect.size.height).addClip()
  237. context?.setFillColor(userColor)
  238. context?.fill(rect)
  239. let textStyle = NSMutableParagraphStyle()
  240. textStyle.alignment = NSTextAlignment.center
  241. let lineHeight = UIFont.systemFont(ofSize: UIFont.systemFontSize).pointSize
  242. NSString(string: initials)
  243. .draw(
  244. in: CGRect(x: 0, y: (size - lineHeight) / 2, width: size, height: lineHeight),
  245. withAttributes: [NSAttributedString.Key.paragraphStyle: textStyle])
  246. avatarImage = UIGraphicsGetImageFromCurrentImageContext()
  247. UIGraphicsEndImageContext()
  248. return avatarImage
  249. }
  250. func convertSVGtoPNGWriteToUserData(svgUrlString: String, fileName: String? = nil, width: CGFloat? = nil, rewrite: Bool, account: String, id: Int? = nil, completion: @escaping (_ imageNamePath: String?, _ id: Int?) -> Void) {
  251. var fileNamePNG = ""
  252. guard let svgUrlString = svgUrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
  253. let iconURL = URL(string: svgUrlString) else {
  254. return completion(nil, id)
  255. }
  256. if let fileName = fileName {
  257. fileNamePNG = fileName
  258. } else {
  259. fileNamePNG = iconURL.deletingPathExtension().lastPathComponent + ".png"
  260. }
  261. let imageNamePath = utilityFileSystem.directoryUserData + "/" + fileNamePNG
  262. if !FileManager.default.fileExists(atPath: imageNamePath) || rewrite == true {
  263. NextcloudKit.shared.downloadContent(serverUrl: iconURL.absoluteString, account: account) { _, data, error in
  264. if error == .success && data != nil {
  265. if let image = UIImage(data: data!) {
  266. var newImage: UIImage = image
  267. if width != nil {
  268. let ratio = image.size.height / image.size.width
  269. let newSize = CGSize(width: width!, height: width! * ratio)
  270. let renderFormat = UIGraphicsImageRendererFormat.default()
  271. renderFormat.opaque = false
  272. let renderer = UIGraphicsImageRenderer(size: CGSize(width: newSize.width, height: newSize.height), format: renderFormat)
  273. newImage = renderer.image { _ in
  274. image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
  275. }
  276. }
  277. guard let pngImageData = newImage.pngData() else {
  278. return completion(nil, id)
  279. }
  280. try? pngImageData.write(to: URL(fileURLWithPath: imageNamePath))
  281. return completion(imageNamePath, id)
  282. } else {
  283. guard let svgImage: SVGKImage = SVGKImage(data: data) else {
  284. return completion(nil, id)
  285. }
  286. if width != nil {
  287. let scale = svgImage.size.height / svgImage.size.width
  288. svgImage.size = CGSize(width: width!, height: width! * scale)
  289. }
  290. guard let image: UIImage = svgImage.uiImage else {
  291. return completion(nil, id)
  292. }
  293. guard let pngImageData = image.pngData() else {
  294. return completion(nil, id)
  295. }
  296. try? pngImageData.write(to: URL(fileURLWithPath: imageNamePath))
  297. return completion(imageNamePath, id)
  298. }
  299. } else {
  300. return completion(nil, id)
  301. }
  302. }
  303. } else {
  304. return completion(imageNamePath, id)
  305. }
  306. }
  307. func getSizePreview(width: Int, height: Int) -> CGSize {
  308. var widthPreview: Double = Double(NCGlobal.shared.sizePreview)
  309. var heightPreview: Double = Double(NCGlobal.shared.sizePreview)
  310. if width > 0, height > 0 {
  311. var ratio: Double = 0
  312. if width >= height {
  313. ratio = Double(width) / Double(height)
  314. heightPreview = widthPreview / ratio
  315. } else {
  316. ratio = Double(height) / Double(width)
  317. widthPreview = heightPreview / ratio
  318. }
  319. }
  320. return CGSize(width: widthPreview, height: heightPreview)
  321. }
  322. func getUserStatus(userIcon: String?, userStatus: String?, userMessage: String?) -> (statusImage: UIImage?, statusMessage: String, descriptionMessage: String) {
  323. var statusImage: UIImage?
  324. var statusMessage: String = ""
  325. var descriptionMessage: String = ""
  326. var messageUserDefined: String = ""
  327. if userStatus?.lowercased() == "online" {
  328. statusImage = loadImage(named: "circle_fill", colors: [UIColor(red: 103.0 / 255.0, green: 176.0 / 255.0, blue: 134.0 / 255.0, alpha: 1.0)])
  329. messageUserDefined = NSLocalizedString("_online_", comment: "")
  330. }
  331. if userStatus?.lowercased() == "away" {
  332. statusImage = loadImage(named: "userStatusAway", colors: [UIColor(red: 233.0 / 255.0, green: 166.0 / 255.0, blue: 75.0 / 255.0, alpha: 1.0)])
  333. messageUserDefined = NSLocalizedString("_away_", comment: "")
  334. }
  335. if userStatus?.lowercased() == "dnd" {
  336. statusImage = loadImage(named: "userStatusDnd")
  337. messageUserDefined = NSLocalizedString("_dnd_", comment: "")
  338. descriptionMessage = NSLocalizedString("_dnd_description_", comment: "")
  339. }
  340. if userStatus?.lowercased() == "offline" || userStatus?.lowercased() == "invisible" {
  341. statusImage = UIImage(named: "userStatusOffline")!.withTintColor(.init(named: "SystemBackgroundInverted")!)
  342. messageUserDefined = NSLocalizedString("_invisible_", comment: "")
  343. descriptionMessage = NSLocalizedString("_invisible_description_", comment: "")
  344. }
  345. if let userIcon = userIcon {
  346. statusMessage = userIcon + " "
  347. }
  348. if let userMessage = userMessage {
  349. statusMessage += userMessage
  350. }
  351. statusMessage = statusMessage.trimmingCharacters(in: .whitespaces)
  352. if statusMessage.isEmpty {
  353. statusMessage = messageUserDefined
  354. }
  355. return(statusImage, statusMessage, descriptionMessage)
  356. }
  357. }