将base64编码转成图片存到本地

网上的转换方式基本都是下面这种,但我转换后就是损坏。

BASE64Decoder decoder = new BASE64Decoder();
//Base64解码
byte[] b = decoder.decodeBuffer(imgfnPhoto);
for (int i = 0; i < b.length; ++i) {
    if (b[i] < 0) {// 调整异常数据
        b[i] += 256;
    }
}
//生成jpg图片
String filename = this.createGUIDService.getGUID()+".jpg";
OutputStream out = new FileOutputStream(request.getRealPath("fsweb/workData/web") + "//" + filename);
out.write(b);
out.flush();
out.close();

改为下面的方式可以成功。

public static void tr(String imageString){
		BufferedImage image = null;
		byte[] imageByte = null;

		try {
			imageByte = DatatypeConverter.parseBase64Binary(imageString);
			ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
			image = ImageIO.read(new ByteArrayInputStream(imageByte));
			bis.close();

			File outputfile = new File("e:\\sealImg.bmp");
			ImageIO.write(image, "bmp", outputfile);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

猜你喜欢

转载自jilin.iteye.com/blog/2318148