2017-05-26 85 views
1

我搜索計算器,我意識到,GetPropertyItem和SetPropertyItem可以在JPEG文件VB.NET撰寫評論,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

基於[MSDN的頁面PropertyItem(HTTPS上:// MSDN。 microsoft.com/en-us/library/system.drawing.imaging.propertyitem(v=vs.110).aspx),'PropertyItem對象用於檢索和更改現有圖像文件的元數據,而不是創建元數據「,所以我不認爲這種方法是正確的。看到[這個答案](https://stackoverflow.com/a/23762564/832052)爲一個完全不同的方法,這似乎做你所需要的。 – djv

+0

@djv感謝您的回答。我想,我之前看到過這個解決方案。而且,我試圖將c#版本轉換爲VB.NET。但是,這並不是很好。我希望我能找到VB.NET的方式來添加評論到JPEG文件:( – NBB

+0

你嘗試使用[**在線轉換器**](http://converter.telerik.com)? –

回答

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