UIImage+Extensions.swift 9.6 KB

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