XML方式传输图片
发布时间:2020-12-16 09:12:35 所属栏目:百科 来源:网络整理
导读:1、把图片读到byte[] 流 2、把byte[]流转为BASE64编码(即是一堆字符串),把字符串放到XML里,图片就可以随着xml传输了。 3、把xml里的BASE64编码解码为byte[]流,把再输出为图片 例子1:简单字符串和BASE64转换 import java.io.IOException;import sun.misc
1、把图片读到byte[] 流
2、把byte[]流转为BASE64编码(即是一堆字符串),把字符串放到XML里,图片就可以随着xml传输了。 3、把xml里的BASE64编码解码为byte[]流,把再输出为图片 例子1:简单字符串和BASE64转换 import java.io.IOException; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; public class TestBase64 { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // 定义一个BASE64Encoder BASE64Encoder encode = new BASE64Encoder(); // 将byte[]转换为base64 String base64 = encode.encode("Darren".getBytes()); // 输出base64 System.out.println(base64); // 新建一个BASE64Decoder BASE64Decoder decode = new BASE64Decoder(); // 将base64转换为byte[] byte[] b = decode.decodeBuffer(base64); // 输出转换后的byte[] System.out.println(new String(b)); } }运行结果: RGFycmVu Darren例子2:图片和BASE64的转换 import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.imageio.ImageIO; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; public class TestImageBase64 { private static final BASE64Encoder encoder = new BASE64Encoder(); private static final BASE64Decoder decoder = new BASE64Decoder(); /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // 得到图片的base64编码 String base64 = getImageBinary("F:/a.jpg","jpg"); // 去掉得到的base64编码的换行符号 Pattern p = Pattern.compile("s*|t|r|n"); Matcher m = p.matcher(base64); String after = m.replaceAll(""); // 打印去掉换行符号base64编码 System.out.println(after); createImage(base64,"F:/b.jpg"); } /* * 得到指定图片的base64编码 */ public static String getImageBinary(String path,String suffix) throws IOException { File f = new File(path); BufferedImage bi = ImageIO.read(f); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bi,suffix,baos); byte[] bytes = baos.toByteArray(); return encoder.encodeBuffer(bytes).trim(); } public static void createImage(String base64Source,String path) throws IOException { byte[] bytes = decoder.decodeBuffer(base64Source); File file = new File(path); FileOutputStream fos = new FileOutputStream(file); fos.write(bytes); fos.flush(); fos.close(); } }
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |