---
title: "将base64编码转成图片存到本地"
author: "jilin"
date: "2016-08-18T11:01:27Z"
tags: ["Image", "Java"]
categories: ["编程语言"]
slug: "base64"
draft: false
lastmod: "2016-08-18T16:09:29Z"
id: 2318148
url: "https://jilin.iteye.com/blog/2318148"
---

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

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