UIImage+Extension.swift 11 KB

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