Base64到底是什么东西呢?
Base64是网络上常见的用于传输8bit字节码的编码方式之一 ,是用来将非ASCII字符的数据转换成ASCII字符的一种方法, 有些人和书本会将编码写成加密算法,这其实是欠妥的。因为任何人拿到编码后的数据都能转化成原始数据,算法是透明的,也不存在秘钥的概念。
为什么要将图片转为base64格式
便于网络传输:由于某些系统中只能使用ASCII字符,Base64就可以将非ASCII字符的数据转换成ASCII字符。举个简单的例子,你使用SMTP协议 (Simple Mail Transfer Protocol 简单邮件传输协议)来发送邮件。因为这个协议是基于文本的协议,所以如果邮件中包含一幅图片,我们知道图片的存储格式是二进制数据(binary data),而非文本格式,我们必须将二进制的数据编码成文本格式,这时候Base 64 Encoding就派上用场了
不可见性:我们知道在计算机中任何数据都是按ascii码存储的,而ascii码的128~255之间的值是不可见字符。而在网络上交换数据时,比如说从A地传到B地,往往要经过多个路由设备,由于不同的设备对字符的处理方式有一些不同,这样那些不可见字符就有可能被处理错误,这是不利于传输的。所以就先把数据先做一个Base64编码,统统变成可见字符,这样出错的可能性就大降低了。
转换过程:
文件转Base64字符串:读取文件的输入流,因为文件流是字节流,所以要放到byte数组(字节数组,byte取值范围-128~127)里,
然后对byte数组做Base64编码,返回字符串。
Base64字符串转文件:对Base64编码的字符串进行Base64解码,得到byte数组,利用文件输出流将byte数据写入到文件。
File转Base64
public static String file2Base64(File file) {
if(file==null) {
return null;
}
String base64 = null;
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
byte[] buff = new byte[fin.available()];
fin.read(buff);
base64 = Base64.encode(buff);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fin != null) {
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return base64;
}
Base64转File
public static File base64ToFile(String base64) {
if(base64==null||"".equals(base64)) {
return null;
}
byte[] buff=Base64.decode(base64);
File file=null;
FileOutputStream fout=null;
try {
file = File.createTempFile("tmp", null);
fout=new FileOutputStream(file);
fout.write(buff);
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fout!=null) {
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return file;
}
文件流转Base64字符串
public static String getBase64FromInputStream(InputStream in) {
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
try {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = in.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
data = swapStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new String(Base64.encodeBase64(data));
}