Base64编码在Web方面有很多应用,譬如在URL、电子邮件方面。有种比较常见的场景就是将图片转换为Base64字符串进行存储。.Net和Java都可以实现此种场景。
.Net Framework也提供了现成的功能类(System.Convert)用于将二进制数据转换为Base64字符串。
将图片转化为Base64字符串的流程是:首先使用BinaryFormatter将图片文件序列化为二进制数据,然后使用Convert类的ToBase64String方法。将Base64字符串转换为图片的流程正好相反:使用Convert类的FromBase64String得到图片文件的二进制数据,然后使用BinaryFormatter反序列化方法。
private void ToBase64(object sender, EventArgs e)
{
Image img = this.pictureBox.Image;
BinaryFormatter binFormatter = new BinaryFormatter();
MemoryStream memStream = new MemoryStream();
binFormatter.Serialize(memStream, img);
byte[] bytes = memStream.GetBuffer();
string base64 = Convert.ToBase64String(bytes);
this.richTextBox.Text = base64;
}
private void ToImage(object sender, EventArgs e)
{
string base64 = this.richTextBox.Text;
byte[] bytes = Convert.FromBase64String(base64);
MemoryStream memStream = new MemoryStream(bytes);
BinaryFormatter binFormatter = new BinaryFormatter();
Image img = (Image)binFormatter.Deserialize(memStream);
this.pictureBox.Image = img;
}
Java方面实现为:
需要导入sun.misc.BASE64Decoder.jar包。
实现代码为:
package com.axbsec.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import Decoder.BASE64Decoder;
public class StringToImg {
public static final int NUMBER=2833;
public static void main(String[] args) {
File fPhotos=new File("C:/Users/Desktop/photos.txt");
File fIDCards=new File("C:/Users /Desktop/idcards.txt");
BufferedReader reader=null;
BufferedReader reader1=null;
String[] fPhotosStr;
String[] fIDCardsStr;
try {
reader=new BufferedReader(new FileReader(fPhotos));
reader1=new BufferedReader(new FileReader(fIDCards));
fPhotosStr = new String[NUMBER];
fIDCardsStr = new String[NUMBER];
String tempString =null;
String tempString1=null;
int line=0;
int line1=0;
while ((tempString=reader.readLine())!=null) {
fPhotosStr[line]=tempString;
line++;
}
reader.close();
while ((tempString1=reader1.readLine())!=null) {
fIDCardsStr[line1]=tempString1;
line1++;
}
reader1.close();
for(int i=0;i<NUMBER;i++){
System.out.println("开始导出图片,第"+(i+1)+"张");
GenerateImage(fPhotosStr[i],"D:/照片集/"+fIDCardsStr[i]+".jpg");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static boolean GenerateImage(String imgStr,String outputFileName) {
if (imgStr == null)
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] b = decoder.decodeBuffer(imgStr);
String imgFilePath = outputFileName;
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
}
通过这两种平台图片转换为Base64的方法展示,就可以轻易的稍作修改完成将图片存储的业务场景了。