1.图片转base64字符串
//图片文件转base64位字符
public static void main(String[] args) throws IOException {
//源文件的磁盘地址
String picPath = "C:\\Users\\ckj\\Desktop\\png\\wyz.jpg";
//base64位保存的地址
String txtPath = "C:\\Users\\ckj\\Desktop\\png\\base64.txt";
BufferedInputStream bf = null;
BufferedOutputStream bo = null;
try {
//使用字节缓冲流读取图片文件数据
bf = new BufferedInputStream(new FileInputStream(picPath));
//获取图片文件大小
int available = bf.available();
//基于图片文件大小,创建缓冲大小
byte[] buff = new byte[available];
//读取整个文件
bf.read(buff);
BASE64Encoder base64 = new BASE64Encoder();
//对文件进行base64编码
String encode = base64.encode(buff);
//字节缓冲输出流
bo = new BufferedOutputStream(new FileOutputStream(txtPath));
//输出到外部
bo.write(encode.getBytes());
} catch (Exception e) {
throw e;
} finally {
//后面创建的流 应该在前面先关闭
if (bo != null) {
bo.close();
}
if (bf != null) {
bf.close();
}
}
}
2.base64字符串转图片(不仅仅是文件,理论上全部东西都可以转,音频,视频,word等等)
public static void main(String[] args) throws IOException {
//文件的磁盘地址
String picPath = "C:\\Users\\ckj\\Desktop\\png\\wyz2.jpg";
//base64位保存的地址
String txtPath = "C:\\Users\\ckj\\Desktop\\png\\base64.txt";
BufferedInputStream bi = null;
BufferedOutputStream bo = null;
try {
//使用字节缓冲流读取文件数据
bi = new BufferedInputStream(new FileInputStream(txtPath));
//获取文件大小
int available = bi.available();
//基于文件大小,创建缓冲大小
byte[] buff = new byte[available];
//读取整个文件
bi.read(buff);
BASE64Decoder base64Decoder = new BASE64Decoder();
//对文件进行base64编码 转码
byte[] bytes = base64Decoder.decodeBuffer(new String(buff));
//字节缓冲输出流
bo = new BufferedOutputStream(new FileOutputStream(picPath));
bo.write(bytes);
} catch (Exception e) {
throw e;
} finally {
//后面创建的流 应该在前面先关闭
if (bo != null) {
bo.close();
}
if (bi != null) {
bi.close();
}
}
}
3.base64字符串直接变图片
找到我们刚刚转换出来的txt文件,如果是图片,在这个txt前面加上
data:image/jpeg;base64,
注意有逗号!!!
转后
直接全选复制,丢到浏览器的请求地址栏即可,注意!!不是丢到百度搜索!!
丢这里