FormatIndicatedCacheSerializer.swift 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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. /// The ``FormatIndicatedCacheSerializer`` enables you to specify an image format for serialized caches.
  34. ///
  35. /// It can serialize and deserialize PNG, JPEG, and GIF images. For images other than these formats, a normalized
  36. /// ``KingfisherWrapper/pngRepresentation()`` will be used.
  37. ///
  38. /// **Example:**
  39. ///
  40. /// ```swift
  41. /// let profileImageSize = CGSize(width: 44, height: 44)
  42. ///
  43. /// // A round corner image.
  44. /// let imageProcessor = RoundCornerImageProcessor(
  45. /// cornerRadius: profileImageSize.width / 2, targetSize: profileImageSize)
  46. ///
  47. /// let optionsInfo: KingfisherOptionsInfo = [
  48. /// .cacheSerializer(FormatIndicatedCacheSerializer.png),
  49. /// .processor(imageProcessor)
  50. /// ]
  51. ///
  52. /// // A URL pointing to a JPEG image.
  53. /// let url = URL(string: "https://example.com/image.jpg")!
  54. ///
  55. /// // The image will always be cached as PNG format to preserve the alpha channel for the round rectangle.
  56. /// // When you load it from the cache later, it will still be round cornered.
  57. /// // Otherwise, the corner part would be filled by a white color (since JPEG does not contain an alpha channel).
  58. /// imageView.kf.setImage(with: url, options: optionsInfo)
  59. /// ```
  60. public struct FormatIndicatedCacheSerializer: CacheSerializer {
  61. /// A ``FormatIndicatedCacheSerializer`` instance that converts images to and from the PNG format.
  62. ///
  63. /// If the image cannot be represented in the PNG format, it will fallback to its actual format determined by the
  64. /// `original` data in ``CacheSerializer/data(with:original:)``.
  65. public static let png = FormatIndicatedCacheSerializer(imageFormat: .PNG, jpegCompressionQuality: nil)
  66. /// A `FormatIndicatedCacheSerializer` which converts image from and to JPEG format. If the image cannot be
  67. /// represented by JPEG format, it will fallback to its real format which is determined by `original` data.
  68. /// The compression quality is 1.0 when using this serializer. If you need to set a customized compression quality,
  69. /// use `jpeg(compressionQuality:)`.
  70. ///
  71. /// A ``FormatIndicatedCacheSerializer`` instance that converts images to and from the JPEG format.
  72. ///
  73. /// If the image cannot be represented in the JPEG format, it will fallback to its actual format determined by the
  74. /// `original` data in ``CacheSerializer/data(with:original:)``.
  75. ///
  76. /// > The compression quality is 1.0 when using this serializer. To set a customized compression quality,
  77. /// use ``FormatIndicatedCacheSerializer/jpeg(compressionQuality:)``.
  78. public static let jpeg = FormatIndicatedCacheSerializer(imageFormat: .JPEG, jpegCompressionQuality: 1.0)
  79. /// A ``FormatIndicatedCacheSerializer`` instance that converts images to and from the JPEG format.
  80. ///
  81. /// - Parameter compressionQuality: The compression quality when converting image to JPEG data.
  82. ///
  83. /// If the image cannot be represented in the JPEG format, it will fallback to its actual format determined by the
  84. /// `original` data in ``CacheSerializer/data(with:original:)``.
  85. public static func jpeg(compressionQuality: CGFloat) -> FormatIndicatedCacheSerializer {
  86. return FormatIndicatedCacheSerializer(imageFormat: .JPEG, jpegCompressionQuality: compressionQuality)
  87. }
  88. /// A ``FormatIndicatedCacheSerializer`` instance that converts images to and from the GIF format.
  89. ///
  90. /// If the image cannot be represented in the GIF format, it will fallback to its actual format determined by the
  91. /// `original` data in ``CacheSerializer/data(with:original:)``.
  92. public static let gif = FormatIndicatedCacheSerializer(imageFormat: .GIF, jpegCompressionQuality: nil)
  93. // The specified image format.
  94. private let imageFormat: ImageFormat
  95. // The compression quality used for lossy image formats (like JPEG).
  96. private let jpegCompressionQuality: CGFloat?
  97. public func data(with image: KFCrossPlatformImage, original: Data?) -> Data? {
  98. func imageData(withFormat imageFormat: ImageFormat) -> Data? {
  99. return autoreleasepool { () -> Data? in
  100. switch imageFormat {
  101. case .PNG: return image.kf.pngRepresentation()
  102. case .JPEG: return image.kf.jpegRepresentation(compressionQuality: jpegCompressionQuality ?? 1.0)
  103. case .GIF: return image.kf.gifRepresentation()
  104. case .unknown: return nil
  105. }
  106. }
  107. }
  108. // generate data with indicated image format
  109. if let data = imageData(withFormat: imageFormat) {
  110. return data
  111. }
  112. let originalFormat = original?.kf.imageFormat ?? .unknown
  113. // generate data with original image's format
  114. if originalFormat != imageFormat, let data = imageData(withFormat: originalFormat) {
  115. return data
  116. }
  117. return original ?? image.kf.normalized.kf.pngRepresentation()
  118. }
  119. public func image(with data: Data, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
  120. return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions)
  121. }
  122. }