Format.swift 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. //
  2. // Format.swift
  3. // Haneke
  4. //
  5. // Created by Hermes Pique on 8/27/14.
  6. // Copyright (c) 2014 Haneke. All rights reserved.
  7. //
  8. import UIKit
  9. public struct Format<T> {
  10. public let name: String
  11. public let diskCapacity : UInt64
  12. public var transform : ((T) -> (T))?
  13. public var convertToData : ((T) -> Data)?
  14. public init(name: String, diskCapacity : UInt64 = UINT64_MAX, transform: ((T) -> (T))? = nil) {
  15. self.name = name
  16. self.diskCapacity = diskCapacity
  17. self.transform = transform
  18. }
  19. public func apply(_ value : T) -> T {
  20. var transformed = value
  21. if let transform = self.transform {
  22. transformed = transform(value)
  23. }
  24. return transformed
  25. }
  26. var isIdentity : Bool {
  27. return self.transform == nil
  28. }
  29. }
  30. public struct ImageResizer {
  31. public enum ScaleMode: String {
  32. case Fill = "fill", AspectFit = "aspectfit", AspectFill = "aspectfill", None = "none"
  33. }
  34. public typealias T = UIImage
  35. public let allowUpscaling : Bool
  36. public let size : CGSize
  37. public let scaleMode: ScaleMode
  38. public let compressionQuality : Float
  39. public init(size: CGSize = CGSize.zero, scaleMode: ScaleMode = .None, allowUpscaling: Bool = true, compressionQuality: Float = 1.0) {
  40. self.size = size
  41. self.scaleMode = scaleMode
  42. self.allowUpscaling = allowUpscaling
  43. self.compressionQuality = compressionQuality
  44. }
  45. public func resizeImage(_ image: UIImage) -> UIImage {
  46. var resizeToSize: CGSize
  47. switch self.scaleMode {
  48. case .Fill:
  49. resizeToSize = self.size
  50. case .AspectFit:
  51. resizeToSize = image.size.hnk_aspectFitSize(self.size)
  52. case .AspectFill:
  53. resizeToSize = image.size.hnk_aspectFillSize(self.size)
  54. case .None:
  55. return image
  56. }
  57. assert(self.size.width > 0 && self.size.height > 0, "Expected non-zero size. Use ScaleMode.None to avoid resizing.")
  58. // If does not allow to scale up the image
  59. if (!self.allowUpscaling) {
  60. if (resizeToSize.width > image.size.width || resizeToSize.height > image.size.height) {
  61. return image
  62. }
  63. }
  64. // Avoid unnecessary computations
  65. if (resizeToSize.width == image.size.width && resizeToSize.height == image.size.height) {
  66. return image
  67. }
  68. let resizedImage = image.hnk_imageByScaling(toSize: resizeToSize)
  69. return resizedImage
  70. }
  71. }