FormatIndicatedCacheSerializer.swift 5.7 KB

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