XML方式传输图片

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();
    }
}


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

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念