Java XML存取二进制图片信息

把图片内容放入XML文件中.

 

  1. public static void main(String[] args) {
  2.         BASE64Encoder encoder=new BASE64Encoder();
  3.         try {
  4.             File f=new File("1_mxz55.jpg");
  5.             if(f.exists())
  6.             {
  7.                 FileInputStream fis=new FileInputStream(f);
  8.                 byte[] buffer=new byte[(int)f.length()];
  9.                 fis.read(buffer);
  10.                 String s_imageData=encoder.encode(buffer);
  11.                 Document doc=DocumentHelper.createDocument();
  12.                 Element root=doc.addElement("ImageList");
  13.                 Element imageID=root.addElement("imageID");
  14.                 Element imageInfo=root.addElement("imageInfo");
  15.                 Element imageSize=root.addElement("imageSize");
  16.                 Element imageData=root.addElement("imageData");
  17.                 imageID.addText("01");
  18.                 imageInfo.addText("图片1");
  19.                 imageSize.addText(String.valueOf(f.length()));
  20.                 imageData.addText(s_imageData);
  21.                 XMLWriter writer=new XMLWriter(new FileOutputStream("image2XML.xml"));
  22.                 writer.write(doc);
  23.                 writer.flush();
  24.                 writer.close();
  25.             }
  26.             
  27.         } catch (FileNotFoundException e) {
  28.             e.printStackTrace();
  29.         } catch (IOException e) {
  30.             e.printStackTrace();
  31.         }
  32.     }

 

取出XML中图片数据

  1. File f=new File("image2XML.xml");
  2.         SAXReader reader=new SAXReader();
  3.         try {
  4.             Document doc=reader.read(f);
  5.             Element root=doc.getRootElement();
  6.             Element image=(Element)root.selectSingleNode("imageData");
  7.             String s_data=image.getText();
  8.             BASE64Decoder decoder=new BASE64Decoder();
  9.             byte[] data=decoder.decodeBuffer(s_data);
  10.             FileOutputStream fos=new FileOutputStream("xxx.jpg");
  11.             fos.write(data);
  12.             fos.flush();
  13.             fos.close();
  14.         } catch (DocumentException e) {
  15.             // TODO Auto-generated catch block
  16.             e.printStackTrace();
  17.         } catch (IOException e) {
  18.             e.printStackTrace();
  19.         }

      

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值