`

用xml来存储图片

    博客分类:
  • java
 
阅读更多
   //将jpg转码,并转成String 
   private String readImage() {   
        BufferedInputStream bis = null;   
        byte[] bytes = null;   
        try {   
            try {   
                bis = new BufferedInputStream(new FileInputStream(ix));   
                bytes = new byte[bis.available()];   
               bis.read(bytes);   
           } finally {   
               if (bis != null) {   
                   bis.close();   
               }   
     
           }   
        } catch (FileNotFoundException e) {   
           e.printStackTrace();   
        } catch (IOException e) {   
           e.printStackTrace();   
        }   
       return new BASE64Encoder().encodeBuffer(bytes);   
     }   

     //将图片转码后存在xml里面 
     public void imageToXml() {   
           String xml = "" + "<image>" + "<name>" + ix + "</name>" + "<content>"   
                    + readImage() + "</content></image>";   
            try {   
                XMLHelper.write(XMLHelper.parseText(xml), ix + ".xml");   
            } catch (DocumentException e) {   
                e.printStackTrace();   
            } catch (IOException e) {   
                e.printStackTrace();   
           }   
     }   

     //从xml读取图片: 
     public void xmlToImage(String rename) {   
            Document d;   
            String name = null;   
            String content = null;   
            try {   
                d = XMLHelper.parse(ix);   
                name = XMLHelper.getNodeValue(d, "/image/name");   
                content = XMLHelper.getNodeValue(d, "/image/content");   
                saveImage(rename.equals("") ? name : rename, content);   
           } catch (DocumentException e) {   
               e.printStackTrace();   
           }   
       }   
     
       public void xmlToImage() {   
           xmlToImage("");   
       }   
     
       private void saveImage(String filename, String content) {   
           try {   
               DataOutputStream dos = null;   
               try {   
                   byte[] bs = new BASE64Decoder().decodeBuffer(content);   
                   dos = new DataOutputStream(new BufferedOutputStream(   
                           new FileOutputStream(filename)));   
                   dos.write(bs);   
               } finally {   
                   dos.close();   
               }   
           } catch (IOException e) {   
               e.printStackTrace();   
           }   
       }   
分享到:
评论
1 楼 Android-DIY 2011-11-18  
谢谢分享。。学习了

相关推荐

Global site tag (gtag.js) - Google Analytics