SwiftImageReadWrite
用于进行基本 CGImage
和 NSImage
/UIImage
类型图像导入/导出的Swift微框架。
为什么?
有时您只需要能以不同格式加载和保存基本图像数据。此框架为常见用例提供了基本包装。
Apple 内置的图像类型功能强大,但在进行不同图像文件类型的导入和导出时可能会相当冗长。正确的导出方法略有难度,因此此框架通过类型安全、格式安全的方式将这一问题抽象化。
在将平台图像转换为 macOS 和其他苹果生态系统时,也存在一些差异,此库将这些差异抽象出来。相同的 API 将在 macOS/iOS/watchOS 和 tvOS 上工作。
它还提供了 CGImage/NSImage/UIImage 的 Codable
包装实现(CGImageCodable
,PlatformImageCodable
),以便在您的 Codable
对象中轻松嵌入图像。
支持类型
- PNG
- JPEG
- TIFF
- GIF
- HEIC
- SVG
表示
所有的编码/转换调用都包裹在图像对象的表示
中。这样做是为了避免与平台中相同名称的图像调用发生冲突。
例如:
let image = UIImage(/* some image */)
let pngData = try image.representation.png(scale: 2)
let image = CGImage(/* some image */)
let pngData = try image.representation.pdf(size: CGSize(width: 300, height: 300))
基本示例
CGImage
// Load a CGImage from raw data
let image = try CGImage.load(imageData: data)
// Export the image as JPG data
let jpegData = try image.representation.jpeg(scale: 3, compression: 0.65, excludeGPSData: true))
// Export the image as PNG data
let pngData = try image.representation.png(scale: 2)
NSImage/UIImage
// Load a CGImage from raw data
let cgImage = CGImage.load(imageData: data)
// Convert to an NSImage or UIImage
let nsImage = cgImage.platformImage(scale: 2)
// Generate a PDF representation of the pdf
let pdf = try cgImage.representation.pdf()
SwiftUI
// Load a CGImage from raw data
let cgImage = CGImage.load(imageData: data)
// Create a SwiftUI image with this image
let swiftUIImage = cgImage.imageUI(scale: 2, label: Text("My Image"))
局限性
NSImage
支持单个图像内的多个图像表示形式。这些例程只处理单个表示形式,因此具有多个存储表示形式的图像将始终仅处理‘最佳’表示形式。
许可证
MIT License
Copyright (c) 2023 Darren Ford
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.