它是 Core Graphics (CG)
的一个封装,提供诸如组合图像(同时调整其方向)或创建大型图像缩略图等功能。请参阅以下示例。
因为它依赖于 CG,所以它已经是多平台的。它支持 iOS (+ iPadOS)、macOS、Mac Catalyst、tvOS 和 watchOS。结果以 CGImage
的形式返回,可以轻松地显示在(例如)NSImage
(AppKit)、UIImage
(UIKit) 或 Image
(SwiftUI) 中。
假设您想组合以下图像
(请注意不同的方向。感谢 这个 repo。)
let imageURLs = [URL] // Suppose this URL array points to the above images.
SImage().combineImages(from: imageURLs) { cgImage, error in
if let resultImage = cgImage {
// Do whatever with the result image.
}
}
(请注意,在此示例中,方向已标准化为 ".up
"。)
let imageURL = URL(string: "My huge image URL")
simage.createThumbnail(from: imageURL) { cgImage in
if let thumbnail = cgImage {
// Do whatever with the thumbnail.
}
}
要使用 最大像素大小创建缩略图
let imageURL = URL(string: "My huge image URL")
let settings = SImageSettings(thumbsMaxPixelSize: "50")
simage.createThumbnail(from: imageURL, settings: settings) { cgImage in
if let thumbnail = cgImage {
// Do whatever with the 50px thumbnail.
}
}
要覆盖默认设置,可以将自定义 SImageSettings
实例作为参数传递给函数。例如
SImage.combineImages(from:👉🏻settings:👈🏻completion:)
SImage.createThumbnail(from:👉🏻settings:👈🏻completion:)
SImage.rotateImages(from:👉🏻settings👈🏻:completion:)
API | 描述 |
---|---|
SImage.combine(images:settings:completion:) |
使用给定的 SImageSettings 组合给定的图像。不修复方向。返回:CGImage 。 |
SImage.combineImages(from:settings:completion:) |
使用给定的 SImageSettings 组合给定 URL 数组中的图像。修复方向(如果可能)。返回:CGImage 。 |
SImage.context(for:settings:) |
使用给定的 CGSize 和 SImageSettings 创建 CGContext 。返回:CGContext 。 |
SImage.createImage(from:) |
从给定的 URL 创建一个 CGImage 。返回:CGImage 。 |
SImage.createThumbnail(from:settings:completion:) |
从给定 URL 的图像创建缩略图。返回:CGImage 。 |
SImage.imageOrientation(from:) |
返回给定 URL 图像的方向 (CGImagePropertyOrientation )。 |
SImage.imageProperties(from:) |
返回给定 URL 图像的所有可用元数据,作为 CGImageProperty (一个 [AnyHashable: Any] 字典)。 |
SImage.imageSize(from:) |
返回给定 URL 图像的 CGSize 。 |
SImage.rotateImages(from:settings:completion:) |
如果图像的方向与设置参数中的目标方向不匹配,则旋转给定 URL 数组中的图像。 返回一个 RotatedImages 数组(一个结构,包含旋转后的 CGImage 及其新的 CGSize )。 注意:某些图像的元数据中可能没有旋转信息。 当 SImage.rotateImages(in:settings:completion:) 遇到这些类型的图像时,它可能会抛出异常 (SImageError.cannotGetImageOrientation(from:))。 要忽略丢失的旋转信息并继续处理下一张图像,请将设置参数中的 rotationIgnoreMissingMetadata 设置为 true (默认值)。 |
SImage.save(image:settings:completion:) |
将给定的 CGImage 以 "SImage.png" 的形式保存在当前用户的临时目录中 (FileManager.default.temporaryDirectory )。 可以通过传入自定义 SImageSettings 实例来覆盖默认选项(文件名、文件类型和目标 URL )。 |
从 2.0.0 版本开始,SImage
可以将其信息输出到 Xcode 的控制台 或 macOS 的控制台应用。
可以按如下方式启用或禁用此行为
var simage = SImage()
simage.enableLogging()
simage.disableLogging()
在 macOS 控制台应用 中,您可以通过 SUBSYSTEM
过滤 SImage
输出:com.backslash-f.SImage
日志记录是通过 AppLogger 完成的,它支持以下版本
使用 Xcode 的 对 SPM 的内置支持(File / Swift Packages / Add Package Dependency
)。
在您的 Package.swift
中,将 SImage
添加为依赖项
dependencies: [
.package(url: "https://github.com/backslash-f/simage", from: "2.0.0")
],
将依赖项与您的目标关联
targets: [
.target(name: "App", dependencies: ["SImage"])
]
运行:swift build