Manchmal ist nötig, Bilder im einem String zu speichern und wieder auszulesen - Beispielsweise dann, wenn der eingestzte Datenbankserver keine Images o.a. speichern kann.
Im folgenden Beispiel eine Klasse zum serialisieren und ein Beispiel zur Verwendung dieser Klasse.
'Zuerst einmal die Klasse
Public Class clsSerialize
Public objImage As Object
<Xml.Serialization.XmlIgnore()> _
Public Property Image() As Image
Get
Dim strToByte() As Byte
strToByte = objImage
Return Image.FromStream(New System.IO.MemoryStream(strToByte))
End Get
Set(ByVal Value As Image)
Dim msMemoryStream As New System.IO.MemoryStream()
Value.Save(msMemoryStream, System.Drawing.Imaging.ImageFormat.Png)
Dim myByte(msMemoryStream.Length - 1) As Byte
msMemoryStream.Position = 0 : msMemoryStream.Read(myByte, 0, msMemoryStream.Length)
objImage = myByte
End Set
End Property
End Class
'Gehen wir nun zum Aufruf.
'Imn diesem Beispiel existiert ein Formular
'mit einer Picturebox und 3 Buttons
Imports System
Imports System.Drawing
Imports System.Xml.Serialization
Imports System.Xml
Public Class Form1
Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoad.Click
Dim ofd As New OpenFileDialog
With ofd
.ShowDialog()
If .FileName <> "" Then
Me.PictureBox1.Image = Image.FromFile(ofd.FileName)
End If
End With
End Sub
Private Sub btnSaveToXml_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveToXml.Click
Dim dlgSave As New SaveFileDialog
With dlgSave
.AddExtension = True
.Filter = "XML|*.xml"
.DefaultExt = "xml"
.InitialDirectory = My.Application.Info.DirectoryPath
.ShowDialog()
Try
If .FileName <> "" Then
Dim Serialize As New clsSerialize()
Serialize.Image = Me.PictureBox1.Image
Dim serializer As New Xml.Serialization.XmlSerializer(GetType(clsSerialize))
Dim xmlWriter As New XmlTextWriter(.FileName, System.Text.Encoding.UTF8)
xmlWriter.Formatting = Formatting.Indented
serializer.Serialize(xmlWriter, Serialize)
xmlWriter.Close()
MessageBox.Show("Serialization Complete", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End With
End Sub
Private Sub btnReadFromXML_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReadFromXML.Click
Dim ofd As New OpenFileDialog
With ofd
Dim deSerialize As clsSerialize
Dim deSerializer As New Xml.Serialization.XmlSerializer(GetType(clsSerialize))
.ShowDialog()
If .FileName <> "" Then
deSerialize = deSerializer.Deserialize(New XmlTextReader(.FileName))
Me.PictureBox1.Image = deSerialize.Image
End If
End With
End Sub
End Class
1 Kommentare zum Snippet