FormatIndicatedCacheSerializer.swift 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. //
  2. // RequestModifier.swift
  3. // Kingfisher
  4. //
  5. // Created by Junyu Kuang on 5/28/17.
  6. //
  7. // Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. import Foundation
  27. import CoreGraphics
  28. #if os(macOS)
  29. import AppKit
  30. #else
  31. import UIKit
  32. #endif
  33. /// `FormatIndicatedCacheSerializer` lets you indicate an image format for serialized caches.
  34. ///
  35. /// It could serialize and deserialize PNG, JPEG and GIF images. For
  36. /// image other than these formats, a normalized `pngRepresentation` will be used.
  37. ///
  38. /// Example:
  39. /// ````
  40. /// let profileImageSize = CGSize(width: 44, height: 44)
  41. ///
  42. /// // A round corner image.
  43. /// let imageProcessor = RoundCornerImageProcessor(
  44. /// cornerRadius: profileImageSize.width / 2, targetSize: profileImageSize)
  45. ///
  46. /// let optionsInfo: KingfisherOptionsInfo = [
  47. /// .cacheSerializer(FormatIndicatedCacheSerializer.png),
  48. /// .processor(imageProcessor)]
  49. ///
  50. /// A URL pointing to a JPEG image.
  51. /// let url = URL(string: "https://example.com/image.jpg")!
  52. ///
  53. /// // Image will be always cached as PNG format to preserve alpha channel for round rectangle.
  54. /// // So when you load it from cache again later, it will be still round cornered.
  55. /// // Otherwise, the corner part would be filled by white color (since JPEG does not contain an alpha channel).
  56. /// imageView.kf.setImage(with: url, options: optionsInfo)
  57. /// ````
  58. public struct FormatIndicatedCacheSerializer: CacheSerializer {
  59. /// A `FormatIndicatedCacheSerializer` which converts image from and to PNG format. If the image cannot be
  60. /// represented by PNG format, it will fallback to its real format which is determined by `original` data.
  61. public static let png = FormatIndicatedCacheSerializer(imageFormat: .PNG, jpegCompressionQuality: nil)
  62. /// A `FormatIndicatedCacheSerializer` which converts image from and to JPEG format. If the image cannot be
  63. /// represented by JPEG format, it will fallback to its real format which is determined by `original` data.
  64. /// The compression quality is 1.0 when using this serializer. If you need to set a customized compression quality,
  65. /// use `jpeg(compressionQuality:)`.
  66. public static let jpeg = FormatIndicatedCacheSerializer(imageFormat: .JPEG, jpegCompressionQuality: 1.0)
  67. /// A `FormatIndicatedCacheSerializer` which converts image from and to JPEG format with a settable compression
  68. /// quality. If the image cannot be represented by JPEG format, it will fallback to its real format which is
  69. /// determined by `original` data.
  70. /// - Parameter compressionQuality: The compression quality when converting image to JPEG data.
  71. public static func jpeg(compressionQuality: CGFloat) -> FormatIndicatedCacheSerializer {
  72. return FormatIndicatedCacheSerializer(imageFormat: .JPEG, jpegCompressionQuality: compressionQuality)
  73. }
  74. /// A `FormatIndicatedCacheSerializer` which converts image from and to GIF format. If the image cannot be
  75. /// represented by GIF format, it will fallback to its real format which is determined by `original` data.
  76. public static let gif = FormatIndicatedCacheSerializer(imageFormat: .GIF, jpegCompressionQuality: nil)
  77. /// The indicated image format.
  78. private let imageFormat: ImageFormat
  79. /// The compression quality used for loss image format (like JPEG).
  80. private let jpegCompressionQuality: CGFloat?
  81. /// Creates data which represents the given `image` under a format.
  82. public func data(with image: KFCrossPlatformImage, original: Data?) -> Data? {
  83. func imageData(withFormat imageFormat: ImageFormat) -> Data? {
  84. return autoreleasepool { () -> Data? in
  85. switch imageFormat {
  86. case .PNG: return image.kf.pngRepresentation()
  87. case .JPEG: return image.kf.jpegRepresentation(compressionQuality: jpegCompressionQuality ?? 1.0)
  88. case .GIF: return image.kf.gifRepresentation()
  89. case .unknown: return nil
  90. }
  91. }
  92. }
  93. // generate data with indicated image format
  94. if let data = imageData(withFormat: imageFormat) {
  95. return data
  96. }
  97. let originalFormat = original?.kf.imageFormat ?? .unknown
  98. // generate data with original image's format
  99. if originalFormat != imageFormat, let data = imageData(withFormat: originalFormat) {
  100. return data
  101. }
  102. return original ?? image.kf.normalized.kf.pngRepresentation()
  103. }
  104. /// Same implementation as `DefaultCacheSerializer`.
  105. public func image(with data: Data, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
  106. return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions)
  107. }
  108. }