Swift JPEG 是一个跨平台的纯 Swift 框架,用于解码、检查、编辑和编码 JPEG 图像。核心框架没有外部依赖,包括 Foundation,并且应该在所有 Swift 平台上编译并提供一致的行为。该框架在 Linux 和 MacOS 上支持额外的功能,例如文件系统支持。
Swift JPEG 在 Mozilla Public License 2.0 许可下可用。示例程序 是公有领域,可以自由改编。
要将 Swift JPEG 添加到项目中,请将此描述符添加到你的 Package.swift
文件中的 dependencies
列表
.package(url: "https://github.com/kelvin13/jpeg", .exact("1.0.0"))
解码图像
import JPEG
func decode(jpeg path:String) throws
{
guard let image:JPEG.Data.Rectangular<JPEG.Common> = try .decompress(path: path)
else
{
// failed to access file from file system
}
let rgb:[JPEG.RGB] = image.unpack(as: JPEG.RGB.self),
size:(x:Int, y:Int) = image.size
// ...
}
编码图像
import JPEG
func encode(jpeg path:String, size:(x:Int, y:Int), pixels:[JPEG.RGB],
compression:Double) // 0.0 = highest quality
throws
{
let layout:JPEG.Layout<JPEG.Common> = .init(
format: .ycc8,
process: .baseline,
components:
[
1: (factor: (2, 2), qi: 0), // Y
2: (factor: (1, 1), qi: 1), // Cb
3: (factor: (1, 1), qi: 1), // Cr
],
scans:
[
.sequential((1, \.0, \.0), (2, \.1, \.1), (3, \.1, \.1)),
])
let jfif:JPEG.JFIF = .init(version: .v1_2, density: (72, 72, .inches))
let image:JPEG.Data.Rectangular<JPEG.Common> =
.pack(size: size, layout: layout, metadata: [.jfif(jfif)], pixels: rgb)
try image.compress(path: path, quanta:
[
0: JPEG.CompressionLevel.luminance( compression).quanta,
1: JPEG.CompressionLevel.chrominance(compression).quanta
])
}