您的位置:首页 > 其它

base64与图片之间的转换

2015-12-07 17:52 260 查看
实现:base64与图片之间的转换 + 上传的简单实现

package com.thinkive.bank.mass.plat.bus.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
* base64与图片之间的转换
* @author xuwx
*
*/
public class GenerateImage {
/**
* @描述 base64转换成图片
* @param imgStr
* @return
*/
public boolean decoder(String imgStr) {
if (null == imgStr)
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; i++) {
if (b[i] < 0) {
b[i] += 256;
}
}
String rootPath=Thread.currentThread().getContextClassLoader().getResource("").toString(); //文件保存根目录位置
rootPath=rootPath.substring(rootPath.indexOf("/")); //重新组合根目录位置
String lastPath=rootPath+"/uploadFile/"; //最终组合的保存文件夹
File file=new File(lastPath);
if(!file.exists())
{
file.mkdir();
}
String nowTime=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()); //时间戳,防止文件重名
String imgFilePath = lastPath+"电子签名("+nowTime+ ").jpg";
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}

/**
* @描述 图片转换成base64
* @param imgStr
* @return
*/
public String encoder()
{
File file=new File("H:/图片/金属合金.jpg");
FileInputStream input=null;
byte[] data =null;
try {
input=new FileInputStream(file);
data=new byte[input.available()];
input.read(data);
input.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}

BASE64Encoder e=new BASE64Encoder();
return e.encode(data);
}
/**
* 测试代码
* @param args
*/
public static void main(String[] args) {
GenerateImage gen=new GenerateImage();
String encoderStr=gen.encoder();
gen.decoder(encoderStr);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: