Image File Operations

Source: Internet
Author: User

I. Operation points:

  • Convert the file to binary, and then convert the binary to a file.
  • Write the file to XML, read it, and display or restore it.
  • Write the file to the database and read it for display or restoration.

Ii. learning knowledge points:

Binary operations: filestream, binaryreader, and binarywriter)

 

3. Procedure:

(1) create a class:Filetodata. CS

Using system; <br/> using system. collections. generic; <br/> using system. LINQ; <br/> using system. web; <br/> using system. io; </P> <p> // <summary> <br/> // Summary of filetodata <br/> /// </Summary> <br/> Public class filetodata <br/>{< br/> Public filetodata () <br/> {<br/> // todo: add the constructor logic here <br/> // <br/>}</P> <p> Public static string filetobinary (string filepath) <br/>{< br/> filestream FS = new filestream (filepath, filemode. open, fileaccess. read); <br/> binaryreader BR = new binaryreader (FS); <br/> int length = (INT) FS. length; <br/> byte [] B = new byte [length]; <br/> for (INT I = 0; I <length; I ++) <br/> {<br/> B [I] = BR. readbyte (); <br/>}< br/> console. writeline ("interval ay: {0}", B); <br/> string strdata = convert. tobase64string (B); // 8-bit unsigned integer array tobase64 <br/> Br. close (); <br/> FS. close (); <br/> // convert the array to a string character <br/> return strdata; </P> <p >}</P> <p> Public static void binarytofile (string path, string binary) <br/>{< br/> filestream FS = new filestream (path, filemode. create, fileaccess. write); <br/> binarywriter BW = new binarywriter (FS); <br/> BW. write (convert. frombase64string (Binary); <br/> BW. close (); // close the binary stream writer <br/> FS. close (); // close the file stream </P> <p >}</P> <p>}

(2) tobinary. aspx ):

Protected void page_load (Object sender, eventargs e) <br/>{< br/> string a = filetodata. filetobinary (server. mappath ("~ /Image 1.jpg "); // convert image 1 to binary <br/> filetodata. binarytofile (server. mappath ("~ /Image 2.jpg "), a); // convert binary to Image 2 </P> <p>}

(3) create a class:Filetoxml. CS

Add namespace: using system. IO; using system. Text; using system. xml;

/// <Summary> <br/> // convert the file to binary <br/> /// </Summary> <br/> public class filetoxml <br/> {<br/> Public filetoxml () <br/>{< br/>}< br/> /// <summary> <br/> // from the upload Control <br/> /// </ summary> <br/> // <Param name = "Fu"> fileupload upload control of the file to be loaded </param> <br/> // <Param name = "xmlpath"> storage location of XML files </param> <br/> // <Param name = "ID"> image id </param> <br/> public static void filetoxml (fileupload Fu, string xmlpath, Guid ID) <br/>{< br/> If (Fu. hasfile) <br/> {// first judge whether the fileupload object contains the file <br/> string pathstring = Fu. filename; <br/> int filelength = Fu. postedfile. contentlength; // only get the file name with the extension </P> <p> try <br/> {<br/> byte [] filebytearray = new byte [filelenght]; <br/> // declare a byte array with the total size of the file to store the binary data to be generated. </P> <p> stream streamobj = Fu. postedfile. inputstream; <br/> // create a stream object that can read the content of the uploaded file </P> <p> streamobj. read (F Ilebytearray, 0, filelength); <br/> // use the stream object reading method. The parameter description stores the data stream in the declared array and reads it from 0, the number of bytes read is all </P> <p> xmldocument xdom = new xmldocument (); </P> <p> If (! File. exists (xmlpath) <br/> {// if no XML exists, create </P> <p> xmldeclaration xdec = xdom. createxmldeclaration ("1.0", "UTF-8", null); <br/> xdom. appendchild (xdec); // create the first line declaration </P> <p> xmlelement root = xdom. createelement ("file"); // create the root node file <br/> xdom. appendchild (Root); </P> <p> xmlelement rootelement = xdom. createelement ("image"); // create the parent node image <br/> root. appendchild (rootelement); </P> <p> xmlelement childelementid = xdom. createelement ("guid"); // image Id field <br/> childelementid. innertext = ID. tostring (); <br/> // use the recent guid number as its serial value <br/> rootelement. appendchild (childelementid); </P> <p> xmlelement childelementimgsize = xdom. createelement ("size"); // file size field <br/> childelementimgsize. innertext = filelength. tostring (); <br/> rootelement. appendchild (childelementimgsize); </P> <p> xmlelement childelementimgdata = xdom. createelement ("imgdata"); // Image Information <br/> childelementimgdata. innertext = convert. tobase64string (filebytearray); <br/> // This sentence is critical. Convert the preceding array to a string and save it <br/> rootelement. appendchild (childelementimgdata); </P> <p> xdom. save (xmlpath ); <br/> // Save the framework created above to the specified XML file <br/>}< br/> else <br/>{// if the XML file exists find the corresponding node directly, then add <br/> xdom. load (xmlpath); // load the XML document <br/> // read the specified XML file to the xmldocument object </P> <p> xmlnode root = xdom. selectsinglenode ("file"); <br/> // use an XPATH expression to find the node that matches the condition, here, of course, it refers to the root node </P> <p> xmlelement rootelement = xdom. createelement ("image"); <br/> root. appendchild (rootelement); <br/> // create a parent node </P> <p> xmlelement childelementid = xdom. createelement ("guid"); // image Id field <br/> childelementid. innertext = ID. tostring (); // uses the recent guid number as its serial value <br/> rootelement. appendchild (childelementid); </P> <p> xmlelement childelementimgsize = xdom. createelement ("size"); <br/> childelementimgsize. innertext = filelenght. tostring (); // file size field <br/> rootelement. appendchild (childelementimgsize); </P> <p> xmlelement childelementimgdata = xdom. createelement ("imgdata"); <br/> childelementimgdata. innertext = convert. tobase64string (Fu. filebytes); <br/> rootelement. appendchild (childelementimgdata); </P> <p> xdom. save (xmlpath ); <br/> // Save the framework created above to the specified XML file <br/>}< br/> catch (exception E) <br/>{< br/> throw E; <br/>}< br/>

(4) write the image file to XML and then read it for display or restoration (filetoxml. aspx ):

Public partial class filetoxml: system. web. UI. page <br/>{< br/> protected void button#click (Object sender, eventargs e) <br/>{// (upload button) write the file into XML <br/> string xmlpath = server. mappath ("~ /App_data/imgxml. XML "); <br/> guid gid = guid. newguid (); <br/> filetoxml. filetoxml (fileupload1, xmlpath, GID); </P> <p> session ["gid"] = GID; <br/>}< br/> protected void button2_click (Object sender, eventargs E) <br/> {// obtain an image based on the GID. <br/> readimgfromxml (guid) session ["gid"]); <br/>}< br/> private void readimgfromxml (guid GID) <br/>{< br/> xmldocument xdom = new xmldocument (); <br/> xdom. load (Ser Ver. mappath ("~ /App_data/imgxml. XML "); </P> <p> xmlnodelist xnl = xdom. selectsinglenode ("// image [guid = '" + GID. tostring () + "']"). childnodes; // find all the subnodes of the node whose guid = the ID we passed in <br/> for (INT I = 0; I <xnl. count; I ++) <br/>{< br/> string imgdata = xnl. item (2 ). innertext; // The third item of the node imgdata <br/> response. outputstream. write (convert. frombase64string (imgdata), 0, imgdata. length); <br/> response. end (); // print all imgd from 0 to the specified length ATA Image Information <br/>}< br/> protected void button3_click (Object sender, eventargs E) <br/> {// read from XML and convert it to a file <br/> xmldocument xdom = new xmldocument (); <br/> xdom. load (server. mappath ("~ /App_data/imgxml. XML "); </P> <p> xmlnodelist xnl = xdom. selectsinglenode ("// image [guid = '" + session ["gid"]. tostring () + "']"). childnodes; <br/> for (INT I = 0; I <xnl. count; I ++) <br/>{< br/> string strdata = xnl. item (2 ). innertext; <br/> filestream FS = new filestream (server. mappath ("~ /Image file name .gif "), filemode. create, fileaccess. write); <br/> binarywriter BW = new binarywriter (FS); <br/> BW. write (convert. frombase64string (strdata); <br/> BW. close (); <br/> FS. close (); <br/>}< br/> image1.imageurl = "~ /Image file name .gif "; <br/>}< br/>

(5) write the image file to the database and then read it for display or restoration (todata. aspx)

Public partial class todata: system. web. UI. page <br/>{< br/> protected void button#click (Object sender, eventargs e) <br/>{</P> <p> guid gid = guid. newguid (); <br/> sqlconnection conn = new sqlconnection (configurationmanager. connectionstrings ["Data Source Name"]. connectionstring); <br/> Conn. open (); <br/> // note: binary data cannot be written to the database by adding strings. </P> <p> sqlcommand cmd = new sqlcommand ("insert into IMG (GID, filedata) values (@ GID, @ filearray) ", Conn); // create a table named IMG and add the field name GID and filedata. Add the field type below <br/> cmd. parameters. add ("@ gid", sqldbtype. uniqueidentifier ). value = GID; <br/> cmd. parameters. add ("@ filearray", sqldbtype. image ). value = fileupload1.filebytes; <br/> cmd. executenonquery (); // execute the SQL statement and return the number of affected rows. <br/> Conn. close (); </P> <p> session ["gid"] = GID; // Save the value of GID <br/>}< br/> protected void button2_click (Object sender, eventargs E) <br/>{< br/> sqlconnection conn = new sqlconnection (configurationmanager. connectionstrings ["Data Source Name"]. connectionstring); <br/> Conn. open (); <br/> sqlcommand cmd = new sqlcommand ("select filedat from IMG where gid = '" + session ["gid"]. tostring () + "'", Conn); <br/> byte [] FBT = (byte []) cmd. executescalar (); <br/> Conn. close (); </P> <p> response. outputstream. write (FBT, 0, FBT. length); <br/> response. end (); </P> <p >}< br/>}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.