jpeg

Tests Documentation

Swift JPEG 是一个跨平台的纯 Swift 框架,用于解码、检查、编辑和编码 JPEG 图像。核心框架没有外部依赖,包括 Foundation,并且应该在所有 Swift 平台上编译并提供一致的行为。该框架在 Linux 和 MacOS 上支持额外的功能,例如文件系统支持。

Swift JPEGApache 2.0 许可证下可用。示例程序 是公有领域,可以自由改编。

文档 · 许可证

要求

swift-jpeg 库需要 Swift 5.10 或更高版本。

平台 状态
🐧 Linux Tests
🍏 Darwin Tests
🍏 Darwin (iOS) iOS
🍏 Darwin (tvOS) tvOS
🍏 Darwin (visionOS) visionOS
🍏 Darwin (watchOS) watchOS

检查最低部署版本

教程和示例程序

API 参考

开始使用

要将 Swift JPEG 添加到项目中,请将此描述符添加到 Package.swift 中的 dependencies 列表

.package(url: "https://github.com/tayloraswift/swift-jpeg", from: "2.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
    ])
}