XML方式传输图片

前端之家收集整理的这篇文章主要介绍了XML方式传输图片前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
1、把图片读到byte[] 流
2、把byte[]流转为BASE64编码(即是一堆字符串),把字符串放到XML里,图片就可以随着xml传输了。

3、把xml里的BASE64编码解码为byte[]流,把再输出图片

例子1:简单字符串和BASE64转换

  1. import java.io.IOException;
  2.  
  3. import sun.misc.BASE64Decoder;
  4. import sun.misc.BASE64Encoder;
  5.  
  6. public class TestBase64 {
  7.  
  8. /**
  9. * @param args
  10. * @throws IOException
  11. */
  12. public static void main(String[] args) throws IOException {
  13. // 定义一个BASE64Encoder
  14. BASE64Encoder encode = new BASE64Encoder();
  15. // 将byte[]转换为base64
  16. String base64 = encode.encode("Darren".getBytes());
  17. // 输出base64
  18. System.out.println(base64);
  19.  
  20. // 新建一个BASE64Decoder
  21. BASE64Decoder decode = new BASE64Decoder();
  22. // 将base64转换为byte[]
  23. byte[] b = decode.decodeBuffer(base64);
  24. // 输出转换后的byte[]
  25. System.out.println(new String(b));
  26. }
  27. }
运行结果:
  1. RGFycmVu
  2. Darren
例子2:图片和BASE64的转换
  1. import java.awt.image.BufferedImage;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.File;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.util.regex.Matcher;
  7. import java.util.regex.Pattern;
  8.  
  9. import javax.imageio.ImageIO;
  10.  
  11. import sun.misc.BASE64Decoder;
  12. import sun.misc.BASE64Encoder;
  13.  
  14. public class TestImageBase64 {
  15. private static final BASE64Encoder encoder = new BASE64Encoder();
  16. private static final BASE64Decoder decoder = new BASE64Decoder();
  17.  
  18. /**
  19. * @param args
  20. * @throws IOException
  21. */
  22. public static void main(String[] args) throws IOException {
  23. // 得到图片的base64编码
  24. String base64 = getImageBinary("F:/a.jpg","jpg");
  25. // 去掉得到的base64编码的换行符号
  26. Pattern p = Pattern.compile("\\s*|\t|\r|\n");
  27. Matcher m = p.matcher(base64);
  28. String after = m.replaceAll("");
  29. // 打印去掉换行符号base64编码
  30. System.out.println(after);
  31.  
  32. createImage(base64,"F:/b.jpg");
  33.  
  34. }
  35.  
  36. /*
  37. * 得到指定图片的base64编码
  38. */
  39. public static String getImageBinary(String path,String suffix) throws IOException {
  40. File f = new File(path);
  41. BufferedImage bi = ImageIO.read(f);
  42. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  43. ImageIO.write(bi,suffix,baos);
  44. byte[] bytes = baos.toByteArray();
  45.  
  46. return encoder.encodeBuffer(bytes).trim();
  47. }
  48.  
  49. public static void createImage(String base64Source,String path) throws IOException {
  50. byte[] bytes = decoder.decodeBuffer(base64Source);
  51. File file = new File(path);
  52. FileOutputStream fos = new FileOutputStream(file);
  53. fos.write(bytes);
  54. fos.flush();
  55. fos.close();
  56. }
  57. }


注:如何解析XML,请参考 XML的几种解析器这篇博客

猜你在找的XML相关文章