PartsRepresentable+Image.swift 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. // Copyright 2024 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import UniformTypeIdentifiers
  15. #if canImport(UIKit)
  16. import UIKit // For UIImage extensions.
  17. #elseif canImport(AppKit)
  18. import AppKit // For NSImage extensions.
  19. #endif
  20. private let imageCompressionQuality: CGFloat = 0.8
  21. /// An enum describing failures that can occur when converting image types to model content data.
  22. /// For some image types like `CIImage`, creating valid model content requires creating a JPEG
  23. /// representation of the image that may not yet exist, which may be computationally expensive.
  24. public enum ImageConversionError: Error {
  25. /// The image that could not be converted.
  26. public enum SourceImage {
  27. #if canImport(UIKit)
  28. case uiImage(UIImage)
  29. #elseif canImport(AppKit)
  30. case nsImage(NSImage)
  31. #endif // canImport(UIKit)
  32. case cgImage(CGImage)
  33. #if canImport(CoreImage)
  34. case ciImage(CIImage)
  35. #endif // canImport(CoreImage)
  36. }
  37. /// The image (the receiver of the call `toModelContentParts()`) was invalid.
  38. case invalidUnderlyingImage
  39. /// A valid image destination could not be allocated.
  40. case couldNotAllocateDestination
  41. /// JPEG image data conversion failed, accompanied by the original image, which may be an
  42. /// instance of `NSImage`, `UIImage`, `CGImage`, or `CIImage`.
  43. case couldNotConvertToJPEG(SourceImage)
  44. }
  45. #if canImport(UIKit)
  46. /// Enables images to be representable as ``ThrowingPartsRepresentable``.
  47. @available(iOS 15.0, macOS 11.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  48. extension UIImage: ThrowingPartsRepresentable {
  49. public func tryPartsValue() throws -> [ModelContent.Part] {
  50. guard let data = jpegData(compressionQuality: imageCompressionQuality) else {
  51. throw ImageConversionError.couldNotConvertToJPEG(.uiImage(self))
  52. }
  53. return [ModelContent.Part.data(mimetype: "image/jpeg", data)]
  54. }
  55. }
  56. #elseif canImport(AppKit)
  57. /// Enables images to be representable as ``ThrowingPartsRepresentable``.
  58. @available(iOS 15.0, macOS 11.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  59. extension NSImage: ThrowingPartsRepresentable {
  60. public func tryPartsValue() throws -> [ModelContent.Part] {
  61. guard let cgImage = cgImage(forProposedRect: nil, context: nil, hints: nil) else {
  62. throw ImageConversionError.invalidUnderlyingImage
  63. }
  64. let bmp = NSBitmapImageRep(cgImage: cgImage)
  65. guard let data = bmp.representation(using: .jpeg, properties: [.compressionFactor: 0.8])
  66. else {
  67. throw ImageConversionError.couldNotConvertToJPEG(.nsImage(self))
  68. }
  69. return [ModelContent.Part.data(mimetype: "image/jpeg", data)]
  70. }
  71. }
  72. #endif
  73. #if !os(watchOS) // This code does not build on watchOS.
  74. /// Enables `CGImages` to be representable as model content.
  75. @available(iOS 15.0, macOS 11.0, macCatalyst 15.0, tvOS 15.0, *)
  76. extension CGImage: ThrowingPartsRepresentable {
  77. public func tryPartsValue() throws -> [ModelContent.Part] {
  78. let output = NSMutableData()
  79. guard let imageDestination = CGImageDestinationCreateWithData(
  80. output, UTType.jpeg.identifier as CFString, 1, nil
  81. ) else {
  82. throw ImageConversionError.couldNotAllocateDestination
  83. }
  84. CGImageDestinationAddImage(imageDestination, self, nil)
  85. CGImageDestinationSetProperties(imageDestination, [
  86. kCGImageDestinationLossyCompressionQuality: imageCompressionQuality,
  87. ] as CFDictionary)
  88. if CGImageDestinationFinalize(imageDestination) {
  89. return [.data(mimetype: "image/jpeg", output as Data)]
  90. }
  91. throw ImageConversionError.couldNotConvertToJPEG(.cgImage(self))
  92. }
  93. }
  94. #endif // !os(watchOS)
  95. #if canImport(CoreImage)
  96. /// Enables `CIImages` to be representable as model content.
  97. @available(iOS 15.0, macOS 11.0, macCatalyst 15.0, tvOS 15.0, *)
  98. extension CIImage: ThrowingPartsRepresentable {
  99. public func tryPartsValue() throws -> [ModelContent.Part] {
  100. let context = CIContext()
  101. let jpegData = (colorSpace ?? CGColorSpace(name: CGColorSpace.sRGB))
  102. .flatMap {
  103. // The docs specify kCGImageDestinationLossyCompressionQuality as a supported option, but
  104. // Swift's type system does not allow this.
  105. // [kCGImageDestinationLossyCompressionQuality: imageCompressionQuality]
  106. context.jpegRepresentation(of: self, colorSpace: $0, options: [:])
  107. }
  108. if let jpegData = jpegData {
  109. return [.data(mimetype: "image/jpeg", jpegData)]
  110. }
  111. throw ImageConversionError.couldNotConvertToJPEG(.ciImage(self))
  112. }
  113. }
  114. #endif // canImport(CoreImage)