UIImage+Extension.swift 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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, size: CGFloat) -> UIImage {
  102. return image(color: color, width: size, height: size)
  103. }
  104. @objc func image(color: UIColor, width: CGFloat, height: CGFloat) -> UIImage {
  105. let size = CGSize(width: width, height: height)
  106. UIGraphicsBeginImageContextWithOptions(.init(width: width, height: height), false, self.scale)
  107. color.setFill()
  108. let context = UIGraphicsGetCurrentContext()
  109. context?.translateBy(x: 0, y: size.height)
  110. context?.scaleBy(x: 1.0, y: -1.0)
  111. context?.setBlendMode(CGBlendMode.normal)
  112. let rect = CGRect(origin: .zero, size: size)
  113. guard let cgImage = self.cgImage else { return self }
  114. context?.clip(to: rect, mask: cgImage)
  115. context?.fill(rect)
  116. let newImage = UIGraphicsGetImageFromCurrentImageContext() ?? self
  117. UIGraphicsEndImageContext()
  118. return newImage
  119. }
  120. func isEqualToImage(image: UIImage?) -> Bool {
  121. if image == nil { return false }
  122. let data1: NSData = self.pngData()! as NSData
  123. let data2: NSData = image!.pngData()! as NSData
  124. return data1.isEqual(data2)
  125. }
  126. class func imageWithView(_ view: UIView) -> UIImage {
  127. UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0)
  128. defer { UIGraphicsEndImageContext() }
  129. view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
  130. return UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
  131. }
  132. func image(alpha: CGFloat) -> UIImage? {
  133. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  134. draw(at: .zero, blendMode: .normal, alpha: alpha)
  135. let newImage = UIGraphicsGetImageFromCurrentImageContext()
  136. UIGraphicsEndImageContext()
  137. return newImage
  138. }
  139. /// Downsamles a image using ImageIO. Has better memory perfomance than redrawing using UIKit
  140. ///
  141. /// - [Source](https://swiftsenpai.com/development/reduce-uiimage-memory-footprint/)
  142. /// - [Original Source, WWDC18](https://developer.apple.com/videos/play/wwdc2018/416/?time=1352)
  143. /// - Parameters:
  144. /// - imageURL: The URL path of the image
  145. /// - pointSize: The target point size
  146. /// - scale: The point to pixel scale (Pixeld per point)
  147. /// - Returns: The downsampled image, if successful
  148. static func downsample(imageAt imageURL: URL, to pointSize: CGSize, scale: CGFloat = UIScreen.main.scale) -> UIImage? {
  149. // Create an CGImageSource that represent an image
  150. let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
  151. guard let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, imageSourceOptions) else { return nil }
  152. // Calculate the desired dimension
  153. let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale
  154. // Perform downsampling
  155. let downsampleOptions = [
  156. kCGImageSourceCreateThumbnailFromImageAlways: true,
  157. kCGImageSourceShouldCacheImmediately: true,
  158. kCGImageSourceCreateThumbnailWithTransform: true,
  159. kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels
  160. ] as CFDictionary
  161. guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions) else { return nil }
  162. // Return the downsampled image as UIImage
  163. return UIImage(cgImage: downsampledImage)
  164. }
  165. // Source:
  166. // https://stackoverflow.com/questions/27092354/rotating-uiimage-in-swift/47402811#47402811
  167. func rotate(radians: Float) -> UIImage? {
  168. var newSize = CGRect(origin: CGPoint.zero, size: self.size).applying(CGAffineTransform(rotationAngle: CGFloat(radians))).size
  169. // Trim off the extremely small float value to prevent core graphics from rounding it up
  170. newSize.width = floor(newSize.width)
  171. newSize.height = floor(newSize.height)
  172. UIGraphicsBeginImageContextWithOptions(newSize, true, self.scale)
  173. let context = UIGraphicsGetCurrentContext()!
  174. // Move origin to middle
  175. context.translateBy(x: newSize.width / 2, y: newSize.height / 2)
  176. // Rotate around middle
  177. context.rotate(by: CGFloat(radians))
  178. // Draw the image at its center
  179. self.draw(in: CGRect(x: -self.size.width / 2, y: -self.size.height / 2, width: self.size.width, height: self.size.height))
  180. let newImage = UIGraphicsGetImageFromCurrentImageContext()
  181. UIGraphicsEndImageContext()
  182. return newImage
  183. }
  184. func colorizeFolder(metadata: tableMetadata, tableDirectory: tableDirectory? = nil) -> UIImage {
  185. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  186. var image = self
  187. if let tableDirectory = tableDirectory {
  188. if let hex = tableDirectory.colorFolder, let color = UIColor(hex: hex) {
  189. image = self.withTintColor(color, renderingMode: .alwaysOriginal)
  190. }
  191. } 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) {
  192. image = self.withTintColor(color, renderingMode: .alwaysOriginal)
  193. }
  194. return image
  195. }
  196. }