Files
stable-diffusion-rpc/Sources/StableDiffusionCore/ImageExtensions.swift

39 lines
1.1 KiB
Swift
Raw Normal View History

2023-04-22 14:52:27 -07:00
import CoreImage
import Foundation
import StableDiffusionProtos
2023-04-22 14:52:27 -07:00
import UniformTypeIdentifiers
extension CGImage {
func toImageData(format: SdImageFormat) throws -> Data {
2023-04-22 14:52:27 -07:00
guard let data = CFDataCreateMutable(nil, 0) else {
throw SdCoreError.imageEncodeFailed
2023-04-22 14:52:27 -07:00
}
guard let destination = try CGImageDestinationCreateWithData(data, formatToTypeIdentifier(format) as CFString, 1, nil) else {
throw SdCoreError.imageEncodeFailed
2023-04-22 14:52:27 -07:00
}
2023-04-22 14:52:27 -07:00
CGImageDestinationAddImage(destination, self, nil)
if CGImageDestinationFinalize(destination) {
return data as Data
} else {
throw SdCoreError.imageEncodeFailed
}
}
func toSdImage(format: SdImageFormat) throws -> SdImage {
let content = try toImageData(format: format)
var image = SdImage()
image.format = format
image.data = content
return image
}
private func formatToTypeIdentifier(_ format: SdImageFormat) throws -> String {
switch format {
case .png: return "public.png"
default: throw SdCoreError.imageEncodeFailed
2023-04-22 14:52:27 -07:00
}
}
}