Writing Images Using XmlWriter
The techniques described in the previous sections can also be used with any sort of binary data that can be expressed with an array of bytes, including images. This section provides you with an example and demonstrates how to embed a JPEG image in an XML document. The structure of the sample XML document is extremely simple. It consists of a single employee node, and inside that node there is an image node holding the binary image data plus an attribute containing the original file name. Code required for implementing this is shown in Listing 4-9.
Listing 4-9: Embedding an Image in an XML Document
<%@ Page Language="C#" %> <%@ Import Namespace="System.Xml" %> <%@ Import Namespace="System.IO" %> <script runat="server">
void Page_Load(object sender, EventArgs e) {
string xmlFilePath = @"C:\Data\Employees.xml"; string imageFileName = ©"C:\Data\Employee.jpg";
using (XmlWriter writer = XmlWriter.Create(xmlFilePath)) {
//Start writing the XML document writer.WriteStartDocument(false); writer.WriteStartElement("employee"); writer.WriteAttributeString("id", "1"); writer.WriteStartElement("image");
writer.WriteAttributeString("fileName", imageFileName);
//Get the size of the file
Filelnfo fi = new Filelnfo(imageFileName);
//Read the JPEG file byte[] imgBytes = new byte[size];
FileStream stream = new FileStream(imageFileName, FileMode.Open);
BinaryReader reader = new BinaryReader(stream);
imgBytes = reader.ReadBytes(size);
reader.Close();
//Write the JPEG data writer.WriteBinHex(imgBytes, 0, size); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument();
//flush the object and write the XML data to the file writer.Flush();
lblResult.Text = "File is written successfully";
catch (Exception ex) {
lblResult.Text = "An Exception occurred: " + ex.Message;
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<title>Writing Images using XmlWriter</title> </head> <body>
<form id="form1" runat="server"> <div>
<asp:label id="lblResult" runat="server" /> </div> </form> </body> </html>
Listing 4-9 uses the Filelnfo class to determine the size of the JPEG file. Filelnfo is a helper class in the System.lO namespace that allows you to retrieve information about individual files. The contents of the employees.jpeg file are extracted using the ReadBytes method of the .NET binary reader. The contents are then encoded as BinHex and written to the XML document. Figure 4-7 shows the output produced by the code.
|
1 5 Cf'Data'iEmHloyees.xml - Microsoft Internet Explorer |
hisibl | |
|
File Edit View Favorites loots Help |
» | |
|
Q Back » _ * [*} I Search Favoiites Media ^ | * |
i a | |
|
Address Jjgjjj C:\Dala\Emploiiees. «ml |
j-J Go I Links |
» |
|
<?xml version=" 1,0* encoding-'utf-8" standalones'no" ?> <employee id="l"> < image fileName='C:\Data\EmploYee jpg,>FFD8FFEOQG104A464946000I01010060G060000GFFDB< </employee> | ||
|
Jt | ||
|
Lli | ||
|
¿J Done |
J My Computer |
Figure 4-7 |
Post a comment