UIImage+Extension.swift 9.3 KB

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