UIImage+Extension.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. //
  2. // UIImage+Extensions.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 27/11/2019.
  6. // Copyright © 2019 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 Foundation
  24. import UIKit
  25. import Accelerate
  26. extension UIImage {
  27. @objc func resizeImage(size: CGSize, isAspectRation: Bool = true) -> UIImage? {
  28. let originRatio = self.size.width / self.size.height
  29. let newRatio = size.width / size.height
  30. var newSize = size
  31. if isAspectRation {
  32. if originRatio < newRatio {
  33. newSize.height = size.height
  34. newSize.width = size.height * originRatio
  35. } else {
  36. newSize.width = size.width
  37. newSize.height = size.width / originRatio
  38. }
  39. }
  40. UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
  41. self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
  42. let newImage = UIGraphicsGetImageFromCurrentImageContext()
  43. UIGraphicsEndImageContext()
  44. if let image = newImage {
  45. return image
  46. }
  47. return self
  48. }
  49. func fixedOrientation() -> UIImage? {
  50. guard imageOrientation != UIImage.Orientation.up else {
  51. // This is default orientation, don't need to do anything
  52. return self.copy() as? UIImage
  53. }
  54. guard let cgImage = self.cgImage else {
  55. // CGImage is not available
  56. return nil
  57. }
  58. guard let colorSpace = cgImage.colorSpace,
  59. let ctx = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else {
  60. return nil // Not able to create CGContext
  61. }
  62. var transform: CGAffineTransform = CGAffineTransform.identity
  63. switch imageOrientation {
  64. case .down, .downMirrored:
  65. transform = transform.translatedBy(x: size.width, y: size.height)
  66. transform = transform.rotated(by: CGFloat.pi)
  67. case .left, .leftMirrored:
  68. transform = transform.translatedBy(x: size.width, y: 0)
  69. transform = transform.rotated(by: CGFloat.pi / 2.0)
  70. case .right, .rightMirrored:
  71. transform = transform.translatedBy(x: 0, y: size.height)
  72. transform = transform.rotated(by: CGFloat.pi / -2.0)
  73. case .up, .upMirrored:
  74. break
  75. @unknown default:
  76. break
  77. }
  78. // Flip image one more time if needed to, this is to prevent flipped image
  79. switch imageOrientation {
  80. case .upMirrored, .downMirrored:
  81. transform = transform.translatedBy(x: size.width, y: 0)
  82. transform = transform.scaledBy(x: -1, y: 1)
  83. case .leftMirrored, .rightMirrored:
  84. transform = transform.translatedBy(x: size.height, y: 0)
  85. transform = transform.scaledBy(x: -1, y: 1)
  86. case .up, .down, .left, .right:
  87. break
  88. @unknown default:
  89. break
  90. }
  91. ctx.concatenate(transform)
  92. switch imageOrientation {
  93. case .left, .leftMirrored, .right, .rightMirrored:
  94. ctx.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))
  95. default:
  96. ctx.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
  97. }
  98. guard let newCGImage = ctx.makeImage() else { return nil }
  99. return UIImage(cgImage: newCGImage, scale: 1, orientation: .up)
  100. }
  101. @objc func image(color: UIColor) -> UIImage {
  102. return image(color: color, width: self.size.width, height: self.size.height)
  103. }
  104. @objc func image(color: UIColor, size: CGFloat) -> UIImage {
  105. return image(color: color, width: size, height: size)
  106. }
  107. @objc func image(color: UIColor, width: CGFloat, height: CGFloat) -> UIImage {
  108. let size = CGSize(width: width, height: height)
  109. UIGraphicsBeginImageContextWithOptions(.init(width: width, height: height), false, self.scale)
  110. color.setFill()
  111. let context = UIGraphicsGetCurrentContext()
  112. context?.translateBy(x: 0, y: size.height)
  113. context?.scaleBy(x: 1.0, y: -1.0)
  114. context?.setBlendMode(CGBlendMode.normal)
  115. let rect = CGRect(origin: .zero, size: size)
  116. guard let cgImage = self.cgImage else { return self }
  117. context?.clip(to: rect, mask: cgImage)
  118. context?.fill(rect)
  119. let newImage = UIGraphicsGetImageFromCurrentImageContext() ?? self
  120. UIGraphicsEndImageContext()
  121. return newImage
  122. }
  123. func isEqualToImage(image: UIImage?) -> Bool {
  124. if image == nil { return false }
  125. let data1: NSData = self.pngData()! as NSData
  126. let data2: NSData = image!.pngData()! as NSData
  127. return data1.isEqual(data2)
  128. }
  129. class func imageWithView(_ view: UIView) -> UIImage {
  130. UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0)
  131. defer { UIGraphicsEndImageContext() }
  132. view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
  133. return UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
  134. }
  135. func image(alpha: CGFloat) -> UIImage? {
  136. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  137. draw(at: .zero, blendMode: .normal, alpha: alpha)
  138. let newImage = UIGraphicsGetImageFromCurrentImageContext()
  139. UIGraphicsEndImageContext()
  140. return newImage
  141. }
  142. /// Downsamles a image using ImageIO. Has better memory perfomance than redrawing using UIKit
  143. ///
  144. /// - [Source](https://swiftsenpai.com/development/reduce-uiimage-memory-footprint/)
  145. /// - [Original Source, WWDC18](https://developer.apple.com/videos/play/wwdc2018/416/?time=1352)
  146. /// - Parameters:
  147. /// - imageURL: The URL path of the image
  148. /// - pointSize: The target point size
  149. /// - scale: The point to pixel scale (Pixeld per point)
  150. /// - Returns: The downsampled image, if successful
  151. static func downsample(imageAt imageURL: URL, to pointSize: CGSize, scale: CGFloat = UIScreen.main.scale) -> UIImage? {
  152. // Create an CGImageSource that represent an image
  153. let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
  154. guard let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, imageSourceOptions) else { return nil }
  155. // Calculate the desired dimension
  156. let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale
  157. // Perform downsampling
  158. let downsampleOptions = [
  159. kCGImageSourceCreateThumbnailFromImageAlways: true,
  160. kCGImageSourceShouldCacheImmediately: true,
  161. kCGImageSourceCreateThumbnailWithTransform: true,
  162. kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels
  163. ] as CFDictionary
  164. guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions) else { return nil }
  165. // Return the downsampled image as UIImage
  166. return UIImage(cgImage: downsampledImage)
  167. }
  168. // Source:
  169. // https://stackoverflow.com/questions/27092354/rotating-uiimage-in-swift/47402811#47402811
  170. func rotate(radians: Float) -> UIImage? {
  171. var newSize = CGRect(origin: CGPoint.zero, size: self.size).applying(CGAffineTransform(rotationAngle: CGFloat(radians))).size
  172. // Trim off the extremely small float value to prevent core graphics from rounding it up
  173. newSize.width = floor(newSize.width)
  174. newSize.height = floor(newSize.height)
  175. UIGraphicsBeginImageContextWithOptions(newSize, true, self.scale)
  176. let context = UIGraphicsGetCurrentContext()!
  177. // Move origin to middle
  178. context.translateBy(x: newSize.width / 2, y: newSize.height / 2)
  179. // Rotate around middle
  180. context.rotate(by: CGFloat(radians))
  181. // Draw the image at its center
  182. self.draw(in: CGRect(x: -self.size.width / 2, y: -self.size.height / 2, width: self.size.width, height: self.size.height))
  183. let newImage = UIGraphicsGetImageFromCurrentImageContext()
  184. UIGraphicsEndImageContext()
  185. return newImage
  186. }
  187. func colorizeFolder(metadata: tableMetadata, tableDirectory: tableDirectory? = nil) -> UIImage {
  188. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  189. var image = self
  190. if let tableDirectory = tableDirectory {
  191. if let hex = tableDirectory.colorFolder, let color = UIColor(hex: hex) {
  192. image = self.withTintColor(color, renderingMode: .alwaysOriginal)
  193. }
  194. } else if let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, serverUrl)), let hex = tableDirectory.colorFolder, let color = UIColor(hex: hex) {
  195. image = self.withTintColor(color, renderingMode: .alwaysOriginal)
  196. }
  197. return image
  198. }
  199. var heic: Data? { heic() }
  200. var cgImageOrientation: CGImagePropertyOrientation { .init(imageOrientation) }
  201. func heic(compressionQuality: CGFloat = 1) -> Data? {
  202. guard
  203. let mutableData = CFDataCreateMutable(nil, 0),
  204. let destination = CGImageDestinationCreateWithData(mutableData, "public.heic" as CFString, 1, nil),
  205. let cgImage = cgImage
  206. else { return nil }
  207. CGImageDestinationAddImage(destination, cgImage, [kCGImageDestinationLossyCompressionQuality: compressionQuality, kCGImagePropertyOrientation: cgImageOrientation.rawValue] as CFDictionary)
  208. guard CGImageDestinationFinalize(destination) else { return nil }
  209. return mutableData as Data
  210. }
  211. }
  212. extension CGImagePropertyOrientation {
  213. init(_ uiOrientation: UIImage.Orientation) {
  214. switch uiOrientation {
  215. case .up: self = .up
  216. case .upMirrored: self = .upMirrored
  217. case .down: self = .down
  218. case .downMirrored: self = .downMirrored
  219. case .left: self = .left
  220. case .leftMirrored: self = .leftMirrored
  221. case .right: self = .right
  222. case .rightMirrored: self = .rightMirrored
  223. @unknown default:
  224. fatalError()
  225. }
  226. }
  227. }