VB.NET以编程方式将注释写入jpeg文件

时间:2017-05-26 17:20:52

标签: vb.net metadata jpeg

我搜索了stackoverflow,我意识到GetPropertyItem和SetPropertyItem可以编辑JPEG文件中的注释

Dim images As Image = System.Drawing.Image.FromFile("C:\\Sample.jpeg")
Dim MSGF As New ArrayList
Dim ID() As String = {"hello ","i am here"}
Dim propItem As PropertyItem = images.GetPropertyItem(40092)
Dim encoderParameters As New EncoderParameters(1)
encoderParameters.Param(0) = New EncoderParameter(Encoder.Quality, 100L)

For i = 0 To ID.Length - 1
    Dim TEMP As String = ID(i)
    For II = 0 To TEMP.Length - 1
        MSGF.Add(Convert.ToInt32(TEMP(II)))
    Next
Next
For i = 0 To MSGF.Count - 1
    propItem.Value.SetValue(Convert.ToByte(MSGF(i)), i)
Next

images.SetPropertyItem(propItem)
images.Save(TextBox1.Text & "\" & "1" & TextBox2.Text)

我意识到我可以通过GetPropertyItem从jpeg文件中获取评论。但是,注释基于ascii代码。因此,我试图将我想要插入的注释转换为ascii代码。

propItem.Value.SetValue(Convert.ToByte(MSGF(i)), i)

此部分实际上已更改已存在于jpeg文件中的注释。 但是,如果jpeg文件中没有注释,则propItem.value.setValue不起作用,因为没有可编辑的内容。

是否只为jpeg文件添加注释?

1 个答案:

答案 0 :(得分:2)

基于this answer in C#,它可以像这样简单:

Dim jpeg = New JpegMetadataAdapter(pathToJpeg)
jpeg.Metadata.Comment = "Some comments"
jpeg.Metadata.Title = "A title"
jpeg.Save()
' Saves the jpeg in-place
jpeg.SaveAs(someNewPath)
' Saves with a new path

这是班级:

Public Class JpegMetadataAdapter
    Private ReadOnly path As String
    Private frame As BitmapFrame
    Public ReadOnly Metadata As BitmapMetadata

    Public Sub New(path As String)
        Me.path = path
        frame = getBitmapFrame(path)
        Metadata = DirectCast(frame.Metadata.Clone(), BitmapMetadata)
    End Sub

    Public Sub Save()
        SaveAs(path)
    End Sub

    Public Sub SaveAs(path As String)
        Dim encoder As New JpegBitmapEncoder()
        encoder.Frames.Add(BitmapFrame.Create(frame, frame.Thumbnail, Metadata, frame.ColorContexts))
        Using stream As Stream = File.Open(path, FileMode.Create, FileAccess.ReadWrite)
            encoder.Save(stream)
        End Using
    End Sub

    Private Function getBitmapFrame(path As String) As BitmapFrame
        Dim decoder As BitmapDecoder = Nothing
        Using stream As Stream = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
            decoder = New JpegBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad)
        End Using
        Return decoder.Frames(0)
    End Function
End Class