利⽤Base64实现图⽚和XML格式的相互转换
package com;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Test {
public static void main(String[] args) {
Test t = new Test();
t.inputToXML();
t.outToImage();
}
// 图⽚转换成XML
public void inputToXML() {
BASE64Encoder encoder = new BASE64Encoder();
try {
File f = new File("D:\\xml\\1.jpg");
// System.out.println("5555");
if (f.exists()) {
FileInputStream fis = new FileInputStream(f);
byte[] buffer = new byte[(int) f.length()];
String s_imageData = de(buffer);
Document doc = ateDocument();
Element root = doc.addElement("ImageList");
Element imageID = root.addElement("imageID");
Element imageInfo = root.addElement("imageInfo");
Element imageSize = root.addElement("imageSize");
Element imageData = root.addElement("imageData");
imageID.addText("01");
imageInfo.addText("图⽚1");
imageSize.addText(String.valueOf(f.length()));
imageData.addText(s_imageData);
XMLWriter writer = new XMLWriter(new FileOutputStream("D:\\xml\\1.xml"));
writer.write(doc);
System.out.println("22");
writer.flush();
writer.close();
} else {
System.out.println("不到要转换的图⽚⽂件!");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// XML转成图⽚
public void outToImage() {
File f = new File("D:\\xml\\1.xml");
SAXReader reader = new SAXReader();
try {
Document doc = ad(f);
byte[] aa = doc.asXML().getBytes() ;
System.out.println(new String(aa,"UTF-8"));
Element root = RootElement();
Element image = (Element) root.selectSingleNode("imageData");
String s_data = Text();
BASE64Decoder decoder = new BASE64Decoder();
byte[] data = decoder.decodeBuffer(s_data);
FileOutputStream fos = new FileOutputStream("D:\\xml\\71198.jpg"); fos.write(data);
fos.flush();
fos.close();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
>使用dom4j解析xml文件
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论