How writing and reading Binary content to a XML file

Posted on 2005-04-27
Last Modified: 2012-06-27

I would like to know how I've to write and read binary content (pictures or other files) into an XMLfile. I think that we've to use the conversion type Base64.

Can someone, please, send me samples? (VB.NET or C#)


Question by:davyberroho
    LVL 9

    Expert Comment

    Real quickly, here's some code that should get you started.  I'm pretty sure it works as is, but I just typed it up and didn't test it.  If it doesn't work let me know and I'll debug it.

    LVL 9

    Assisted Solution

    // Serialization: image to base64
    Image img = new Bitmap(@"c:\image.gif");
    MemoryStream ms = new MemoryStream();
    img.Save(ms, ImageFormat.Gif);

    StringBuilder sb= new StringBuilder();
    StringWriter sw= new StringWriter(sb);
    XmlTextWriter xtw = new XmlTextWriter(sw);

    XmlSerializer xs = new XmlSerializer(ms.GetBuffer().GetType());
    xs.Serialize(xtw, ms.GetBuffer());

    // finished text (put this into your xml file)
    string serializedImage = sb.ToString();

    // Deserialization: base64 to image
    XmlTextReader xtr = new XmlTextReader(new StringReader(serializedImage));
    Image img = new Bitmap(new MemoryStream((byte[])xs.Deserialize(xtr)));
    LVL 28

    Accepted Solution

    Convert image to XML and back

    'rename form to frm_UI

    Imports System.IO
    Imports System.Text
    Imports System.Xml
    Imports System.Drawing.Imaging

    Public Class frm_UI
        Inherits System.Windows.Forms.Form

    #Region " Windows Form Designer generated code "

        Public Sub New()

            'This call is required by the Windows Form Designer.

            'Add any initialization after the InitializeComponent() call

        End Sub

        'Form overrides dispose to clean up the component list.
        Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                If Not (components Is Nothing) Then
                End If
            End If
        End Sub

        'Required by the Windows Form Designer
        Private components As System.ComponentModel.IContainer

        'NOTE: The following procedure is required by the Windows Form Designer
        'It can be modified using the Windows Form Designer.  
        'Do not modify it using the code editor.
        Friend WithEvents txt_Source As System.Windows.Forms.TextBox
        Friend WithEvents Label1 As System.Windows.Forms.Label
        Friend WithEvents OFD_SelectFile As System.Windows.Forms.OpenFileDialog
        Friend WithEvents btn_Browse As System.Windows.Forms.Button
        Friend WithEvents PB_sample As System.Windows.Forms.PictureBox
        Friend WithEvents btn_RW As System.Windows.Forms.Button
        Friend WithEvents Label2 As System.Windows.Forms.Label
        Friend WithEvents lbl_Message As System.Windows.Forms.Label
        Friend WithEvents lbl_Title As System.Windows.Forms.Label
        <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
            Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(frm_UI))
            Me.txt_Source = New System.Windows.Forms.TextBox()
            Me.btn_Browse = New System.Windows.Forms.Button()
            Me.Label1 = New System.Windows.Forms.Label()
            Me.lbl_Message = New System.Windows.Forms.Label()
            Me.OFD_SelectFile = New System.Windows.Forms.OpenFileDialog()
            Me.PB_sample = New System.Windows.Forms.PictureBox()
            Me.btn_RW = New System.Windows.Forms.Button()
            Me.Label2 = New System.Windows.Forms.Label()
            Me.lbl_Title = New System.Windows.Forms.Label()
            Me.txt_Source.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
            Me.txt_Source.Location = New System.Drawing.Point(87, 44)
            Me.txt_Source.Name = "txt_Source"
            Me.txt_Source.Size = New System.Drawing.Size(240, 21)
            Me.txt_Source.TabIndex = 0
            Me.txt_Source.Text = ""
            Me.btn_Browse.FlatStyle = System.Windows.Forms.FlatStyle.Flat
            Me.btn_Browse.Location = New System.Drawing.Point(335, 44)
            Me.btn_Browse.Name = "btn_Browse"
            Me.btn_Browse.Size = New System.Drawing.Size(73, 21)
            Me.btn_Browse.TabIndex = 1
            Me.btn_Browse.Text = "Browse..."
            Me.Label1.AutoSize = True
            Me.Label1.Location = New System.Drawing.Point(8, 49)
            Me.Label1.Name = "Label1"
            Me.Label1.Size = New System.Drawing.Size(69, 14)
            Me.Label1.TabIndex = 2
            Me.Label1.Text = "Select File :"
            Me.lbl_Message.ForeColor = System.Drawing.Color.Blue
            Me.lbl_Message.Location = New System.Drawing.Point(8, 106)
            Me.lbl_Message.Name = "lbl_Message"
            Me.lbl_Message.Size = New System.Drawing.Size(520, 58)
            Me.lbl_Message.TabIndex = 3
            Me.lbl_Message.Text = "Please select Image/XML for encoding."
            Me.PB_sample.Anchor = (((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                        Or System.Windows.Forms.AnchorStyles.Left) _
                        Or System.Windows.Forms.AnchorStyles.Right)
            Me.PB_sample.BackColor = System.Drawing.Color.White
            Me.PB_sample.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
            Me.PB_sample.Image = CType(resources.GetObject("PB_sample.Image"), System.Drawing.Bitmap)
            Me.PB_sample.Location = New System.Drawing.Point(8, 200)
            Me.PB_sample.Name = "PB_sample"
            Me.PB_sample.Size = New System.Drawing.Size(536, 328)
            Me.PB_sample.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage
            Me.PB_sample.TabIndex = 4
            Me.PB_sample.TabStop = False
            Me.btn_RW.Enabled = False
            Me.btn_RW.FlatStyle = System.Windows.Forms.FlatStyle.Flat
            Me.btn_RW.Location = New System.Drawing.Point(87, 72)
            Me.btn_RW.Name = "btn_RW"
            Me.btn_RW.Size = New System.Drawing.Size(240, 23)
            Me.btn_RW.TabIndex = 5
            Me.btn_RW.Text = "Read and Write Image / XML files"
            Me.Label2.Location = New System.Drawing.Point(8, 172)
            Me.Label2.Name = "Label2"
            Me.Label2.Size = New System.Drawing.Size(100, 16)
            Me.Label2.TabIndex = 6
            Me.Label2.Text = "Image Preview :"
            Me.lbl_Title.Anchor = ((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                        Or System.Windows.Forms.AnchorStyles.Right)
            Me.lbl_Title.BackColor = System.Drawing.Color.Gray
            Me.lbl_Title.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
            Me.lbl_Title.Font = New System.Drawing.Font("Arial", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.lbl_Title.ForeColor = System.Drawing.Color.White
            Me.lbl_Title.Location = New System.Drawing.Point(6, 3)
            Me.lbl_Title.Name = "lbl_Title"
            Me.lbl_Title.Size = New System.Drawing.Size(540, 32)
            Me.lbl_Title.TabIndex = 10
            Me.AutoScaleBaseSize = New System.Drawing.Size(6, 14)
            Me.ClientSize = New System.Drawing.Size(552, 590)
            Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.lbl_Title, Me.Label2, Me.btn_RW, Me.PB_sample, Me.lbl_Message, Me.Label1, Me.btn_Browse, Me.txt_Source})
            Me.Font = New System.Drawing.Font("Arial", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.Name = "frm_UI"
            Me.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show
            Me.Text = "Binary In Xml ( Encoding / Decoding )"

        End Sub

    #End Region

        Dim m_SourceEXT As String
        Dim m_TargetFile As String

        Private Sub btn_Browse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Browse.Click
            Dim MyImage As Bitmap
            Me.PB_sample.Image = Nothing
            m_SourceEXT = ""
            OFD_SelectFile.Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG|XML Files (*.XML)|*.XML"
            If OFD_SelectFile.ShowDialog <> DialogResult.OK Then Exit Sub
            Me.txt_Source.Text = OFD_SelectFile.FileName

            m_SourceEXT = Mid(Me.txt_Source.Text, Me.txt_Source.Text.LastIndexOf(".") + 2)  'check extension

            If m_SourceEXT.ToUpper = "XML" Then
                btn_RW.Text = "Read XML and Write as Image"
                m_TargetFile = Replace(Me.txt_Source.Text, ".xml", ".[Source Extension]")
                MyImage = New Bitmap(Me.txt_Source.Text)
                If MyImage.Width <= PB_sample.Width And MyImage.Height <= PB_sample.Height Then
                    Me.PB_sample.SizeMode = PictureBoxSizeMode.CenterImage
                    Me.PB_sample.SizeMode = PictureBoxSizeMode.StretchImage
                End If
                Me.PB_sample.Image = CType(MyImage, Image)
                btn_RW.Text = "Read Image and Write to XML"
                m_TargetFile = Mid(Me.txt_Source.Text, 1, Me.txt_Source.Text.LastIndexOf(".") + 1) & "xml"
            End If

            lbl_Message.Text = "Source File : " & Me.txt_Source.Text & vbCrLf & "Target File : " & m_TargetFile
            btn_RW.Enabled = True
        End Sub

        Private Sub btn_RW_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_RW.Click
            If m_SourceEXT.ToUpper = "XML" Then
            End If
        End Sub

    #Region " Conversion Methods "
        Private Sub WriteXMLPicture()
            'it saved in the same folder as picture
            Dim xml_textwriter As New XmlTextWriter(m_TargetFile, Encoding.UTF8)
            xml_textwriter.Formatting = Formatting.Indented

            ' Copy the picture into a MemoryStream.
            Dim memory_stream As New MemoryStream()
            Dim OriginalImage As Image

            OriginalImage = New Bitmap(Me.txt_Source.Text)
            OriginalImage.Save(memory_stream, GetFormat(m_SourceEXT))

            ' Copy the MemoryStream data into a Byte array.
            Dim bytes(memory_stream.Length - 1) As Byte
            bytes = memory_stream.ToArray()

            ' Make a Picture element.
            xml_textwriter.WriteAttributeString("Encoding", Nothing, "Base64")
            ' Save Image details and encoding as Attributes

            xml_textwriter.WriteAttributeString("Bytes", bytes.Length)
            xml_textwriter.WriteAttributeString("Height", OriginalImage.Height)
            xml_textwriter.WriteAttributeString("Width", OriginalImage.Width)
            xml_textwriter.WriteAttributeString("Type", m_SourceEXT)
            xml_textwriter.WriteBase64(bytes, 0, bytes.Length)

            MsgBox("XML file created successfully ! ", MsgBoxStyle.Information, "Success !")

        End Sub

        Private Sub ReadXMLPicture()
            Dim OriginalImage As Image
            Dim _ValidXML As Boolean = False
            Dim ImgExt As String = ""

            ' Load the picture from XML
            Dim xml_textreader As New XmlTextReader(Me.txt_Source.Text)

            ' Skip until we find the Picture node.
            Do While xml_textreader.Read()
                ' See if this is the Picture node.
                If xml_textreader.Name = "Picture" Then
                    _ValidXML = True
                    ' Allocate room for the byte data and get all attribute values.
                    Dim num_bytes As Integer = xml_textreader.GetAttribute("Bytes")
                    Dim h As Integer = xml_textreader.GetAttribute("Height")
                    Dim w As Integer = xml_textreader.GetAttribute("Width")

                    ImgExt = xml_textreader.GetAttribute("Type")

                    'Refresh the target file according to parameters read from XML file Type Attribute
                    m_TargetFile = Replace(Me.txt_Source.Text, ".xml", "." & ImgExt)
                    lbl_Message.Text = "Source File : " & Me.txt_Source.Text & vbCrLf & "Target File : " & m_TargetFile

                    Dim bytes(num_bytes - 1) As Byte

                    ' Translate the encoded data back into byte data.
                    Select Case xml_textreader.GetAttribute("Encoding").ToLower
                        Case "base64"
                            xml_textreader.ReadBase64(bytes, 0, num_bytes)
                        Case "binhex"
                            xml_textreader.ReadBinHex(bytes, 0, num_bytes)
                        Case Else
                            MsgBox("Unknown image encoding '" & xml_textreader.GetAttribute("Encoding") & "'", _
                                MsgBoxStyle.Exclamation, "Unknown Encoding")
                            Exit Sub
                    End Select

                    ' Allocate a MemoryStream and a BinaryWriter attached to it.
                    Dim memory_stream As New MemoryStream()
                    Dim binary_writer As BinaryWriter = New BinaryWriter(memory_stream)

                    ' Copy the bytes into the BinaryWriter and MemoryStream.
                    binary_writer.Write(bytes, 0, num_bytes)

                    ' Load the picture from the memory stream and save it and show in the Picture box.
                    memory_stream.Position = 0
                    OriginalImage = Image.FromStream(memory_stream)

                    OriginalImage.Save(m_TargetFile, GetFormat(ImgExt))
                    Me.PB_sample.Image = Image.FromStream(memory_stream)
                    PB_sample.SizeMode = PictureBoxSizeMode.CenterImage
                    Exit Do
                End If

            If _ValidXML Then
                MsgBox(ImgExt.ToUpper & " file created successfully ! ", MsgBoxStyle.Information, "Success !")
                MsgBox("Invalid XML file format ! ", MsgBoxStyle.Critical, "Error !")
            End If
        End Sub
    #End Region

        Private Function GetFormat(ByVal ImageType As String) As System.Drawing.Imaging.ImageFormat
            Select Case ImageType.ToUpper
                Case "JPG"
                    Return ImageFormat.Jpeg
                Case "GIF"
                    Return ImageFormat.Gif
                Case "PNG"
                    Return ImageFormat.Png
                Case "BMP"
                    Return ImageFormat.Bmp
            End Select
        End Function

        Private Sub frm_UI_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            lbl_Title.Text = "This Utility can be used to Convert (encode) Image Files to XML and vice versa." & vbCrLf & _
                                "It supports PNG, JPG, GIF && BMP image files."
        End Sub
    End Class

    Author Comment

    Thanks  iboutchkine !!!

    Great sample!


    Featured Post

    Why You Should Analyze Threat Actor TTPs

    After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

    Join & Write a Comment

    This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
    A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
    Hi everyone! This is Experts Exchange customer support.  This quick video will show you how to change your primary email address.  If you have any questions, then please Write a Comment below!
    Here's a very brief overview of the methods PRTG Network Monitor ( offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

    746 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now