@@ -173,7 +173,47 @@ extension Image { // Gray
173173 intent: CGColorRenderingIntent . defaultIntent
174174 ) !
175175 }
176-
176+
177+ internal static func withGeneratedCGImage< R, Pixel> (
178+ image: Image < Pixel > ,
179+ colorSpace: CGColorSpace ,
180+ bitmapInfo: CGBitmapInfo ,
181+ body: ( CGImage ) throws -> R
182+ ) rethrows -> R {
183+ var image = image
184+ let bytesPerPixel = MemoryLayout< Pixel> . size
185+ let length = image. count * bytesPerPixel
186+ let width = image. width
187+ let height = image. height
188+
189+ return try image. pixels. withUnsafeMutableBytes { bytes in
190+ let provider : CGDataProvider = CGDataProvider ( data: Data (
191+ bytesNoCopy: bytes. baseAddress!,
192+ // `baseAddress` is `nil` if `bytes.count` is `0`.
193+ // However creating a `CGImage` with 0 pixels is illegal.
194+ // So calling this method with empty images are logic failures
195+ // and using `!` is justified.
196+ count: length,
197+ deallocator: . none
198+ ) as CFData ) !
199+
200+ let cgImage = CGImage (
201+ width: width,
202+ height: height,
203+ bitsPerComponent: bytesPerPixel * 8 ,
204+ bitsPerPixel: bytesPerPixel * 8 ,
205+ bytesPerRow: bytesPerPixel * width,
206+ space: colorSpace,
207+ bitmapInfo: bitmapInfo,
208+ provider: provider,
209+ decode: nil ,
210+ shouldInterpolate: false ,
211+ intent: CGColorRenderingIntent . defaultIntent
212+ ) !
213+
214+ return try body ( cgImage)
215+ }
216+ }
177217}
178218
179219#endif
0 commit comments