ios - 在图像文件头上添加注释

标签 ios swift file uiimage metadata

我想在图像文件标题中添加评论。因为我可以在 UserComment 下添加对 EXIF 元数据的评论,但我想在图像文件头中添加多个评论。

我使用哪个框架?对于 UserComment,我使用的是 ImageIO 框架。

最佳答案

以下是如何在 Swift 中向 JPEG 图像添加注释(即不是 EXIF UserComment)。我不认为它可以使用 ImageIO 框架来完成。

代码来自 wrjpgcom 命令行工具,用 C 语言编写。它是 libjpeg 库的一部分。检查source code以获得更详细的评论(它实际上并不使用 libjpeg)。

We will insert the new comment marker just before SOFn. This (a) causes the new comment to appear after, rather than before, existing comments; and (b) ensures that comments come after any JFIF or JFXX markers, as required by the JFIF specification.

import Foundation

func addJPEGComment(to jpegData: inout Data, _ comment: String) {

    // find index of first SOF marker, or EOI
    let sofMarkers: [UInt8] = [
        0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6,
        0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE,
        0xCF, 0xD9 // EOI
    ]

    var firstSOFRange: Range<Data.Index>?
    for marker in sofMarkers {
        if let range = jpegData.range(of: Data(bytes: [ 0xFF, marker ])) {
            firstSOFRange = range
            break
        }
    }

    guard let firstSOFIndex = firstSOFRange?.lowerBound
        else { fatalError("No SOF or EOI marker found.") }

    // create comment byte array
    let length = comment.lengthOfBytes(using: .utf8) + 2
    let l1 = UInt8((length >> 8) & 0xFF)
    let l2 = UInt8(length & 0xFF)
    let commentArray = [ 0xFF, 0xFE /* COM marker */, l1, l2 ] + [UInt8](comment.utf8)

    // insert comment array into image data object
    jpegData.insert(contentsOf: commentArray, at: firstSOFIndex)
}

guard let jpegURL = Bundle.main.url(forResource: "no_com", withExtension: "jpg")
    else { fatalError("File not found.") }

guard var jpegData = try? Data(contentsOf: jpegURL)
    else { fatalError("File could not be read.") }

addJPEGComment(to: &jpegData, "This is a JPEG comment.")

guard let jpegOutputURL = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("with_com.jpg")
    else { fatalError("Destination URL not created") }

try jpegData.write(to: jpegOutputURL)

print(jpegOutputURL)

( Gist )

当输出 JPEG 上传到 this 时显示注释网站:

enter image description here

关于ios - 在图像文件头上添加注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43465281/

相关文章:

ios - 使用 Storyboard ios7 在选项卡栏 Controller 中设置所选图像

ios - 如何在日历中设置默认提醒?

iphone - 如何从项目内部调用ViewController?

ios - 当键盘快速出现时向上滚动 UITableView

Javadoc 多行声明语法?

java - 在 Java 中获取所有 DVD 驱动器

iphone - NSFetchedResultsController sectionNameKeyPath 等效于 EKEventStore 从 iPhone 日历中获取的事件

swift - CocoaPods 今日扩展

SwiftUI:在使用常量与@Binding 初始值设定项时了解 .sheet/.fullScreenCover 生命周期

java - 删除文件总是失败