一个跨平台的 Swift 库,用于处理各种图像文件格式。
.png
:使用 pnggroup/libpng (通过 the-swift-collective/libpng).jpeg
:使用 tayloraswift/jpeg.webp
:使用 webmproject/libwebp (通过 the-swift-collective/libwebp)未来,我希望添加对位图、gif 和 heic 文件的支持。
加载图像有很多不同的方法。您使用哪一种方法取决于您对要加载的图像了解多少。 在此示例中,我们将让 Image
使用文件扩展名来检测文件格式,但您也可以直接提供字节,它将从文件的前几个字节检测图像格式。 如果您预先知道文件格式,则可以使用 Image.load(from:as:)
。
import Foundation
import ImageFormats
let url = URL(fileURLWithPath: "image.png")
let bytes = [UInt8](try Data(contentsOf: url))
let image = Image<RGBA>.load(from: bytes, usingFileExtension: fileExtension)
print("width = \(image.width)")
print("height = \(image.height)")
print("pixel @ (0, 0) = \(image[row: 0][column: 0])")
import Foundation
import ImageFormats
let image: Image<RGBA> = ...
let url = URL(fileURLWithPath: "image.png")
let pngBytes = try image.encodeToPNG()
try Data(pngBytes).write(to: url)
let bytes: [UInt8] = [...]
let format = Image.detectFormat(of: bytes)
let rgbaImage: Image<RGBA> = ...
let rgbImage = rgbaImage.convert(to: RGB.self)
struct Grayscale: BytesConvertible, RGBAConvertible {
static let stride = 1
var luminosity: UInt8
var rgba: RGBA {
RGBA(
luminosity,
luminosity,
luminosity,
255
)
}
init(_ luminosity: UInt8) {
self.luminosity = luminosity
}
init(from rgba: RGBA) {
luminosity = (rgba.red * 299 + rgba.green * 587 + rgba.blue * 114) / 1000
}
func encode(to array: inout [UInt8], at offset: Int) {
array[offset] = luminosity
}
static func decode(_ bytes: ArraySlice<UInt8>) -> Self {
return Self(bytes[bytes.startIndex])
}
}
您现在可以将任何格式的图像转换为灰度。 所有转换都通过 RGBA
进行。
let image: Image<RGB> = ...
let grayscale = image.convert(to: Grayscale.self)
尚未实现。