Dim stream = New FileStream(imagepath, FileMode.Open, FileAccess.Read)
Dim decoder = New JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.None)
Dim metadata = TryCast(decoder.Frames(0).Metadata, BitmapMetadata)
If metadata IsNot Nothing Then
Keywords.Text = metadata.Keywords.Aggregate(Function(old, val) Convert.ToString(old) & "; " & Convert.ToString(val))
End If
Dim bitmapFrame = decoder.Frames(0)
metadata = bitmapFrame.Metadata.Clone()
metadata.Keywords = New ReadOnlyCollection(Of String)(New List(Of String)(New String() {"test1", "test2"}))
Dim stream1 = New FileStream(imagepath1, FileMode.Create)
Dim encoder = New JpegBitmapEncoder()
encoder.Frames.Add(bitmapFrame.Create(bitmapFrame, bitmapFrame.Thumbnail, metadata, bitmapFrame.ColorContexts))
encoder.Save(stream1)
更新
新代码替换图像。
Imports System.Windows.Media.Imaging
Imports System.IO
Imports System.Collections.ObjectModel
Class MainWindow
Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
Dim imagepath = ".\img.jpg" ' path to file
Dim stream = New FileStream(imagepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim decoder = New JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.None)
Dim metadata = TryCast(decoder.Frames(0).Metadata, BitmapMetadata)
If metadata IsNot Nothing Then
Keywords.Text = metadata.Keywords.Aggregate(Function(old, val) Convert.ToString(old) & "; " & Convert.ToString(val))
End If
Description.Text = metadata.GetQuery("/app13/irb/8bimiptc/iptc/Caption") 'get description
Dim bitmapFrame = decoder.Frames(0)
metadata = bitmapFrame.Metadata.Clone()
Dim newkeywords As New List(Of String)(New String() {"test1", "test2"})
newkeywords.AddRange(metadata.Keywords) ' this strin adds old keywords
metadata.Keywords = New ReadOnlyCollection(Of String)(newkeywords) 'replace keywords
metadata.SetQuery("/app13/irb/8bimiptc/iptc/Caption", "My test picture1.") ' set new description
Dim memstream As New MemoryStream() ' create temp storage in memory
Dim encoder = New JpegBitmapEncoder()
encoder.Frames.Add(bitmapFrame.Create(bitmapFrame, bitmapFrame.Thumbnail, metadata, bitmapFrame.ColorContexts))
encoder.Save(memstream) ' save in memory
stream.Close()
stream = New FileStream(imagepath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite)
memstream.Seek(0, System.IO.SeekOrigin.Begin) ' go to stream start
Dim bytes(memstream.Length) As Byte
memstream.Read(bytes, 0, memstream.Length)
stream.Write(bytes, 0, bytes.Length)
stream.Close()
memstream.Close()
End Sub
End Class
jpeg 元数据在这里。
IPTC 字段在这里。