本篇文章中图片的上传是通过二进制的形式进行传输,在前台首先获取图片的二进制形式,再通过Base64对二进制进行编码进行传输代码如下:
//获取手机中的图片
Bitmap bitmap = BitmapFactory.decodeFile(path);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
//清空画图缓存否则下次获取图片时还是原图片
if (null != bitmap) {
//对图片进行压缩,100为不压缩,并写入字节流中
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
}
//获取图片的二进制
byte[] compress_head_photo = bos.toByteArray();
try {
bos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
//对二进制数组进行编码
String result = Base64.encodeToString(compress_head_photo, Base64.DEFAULT);
后台解码过程:
public void savePicture(String head_photo, String name) {
BASE64Decoder decoder = new BASE64Decoder();
FileOutputStream output = null;
file = new File(FOLDER + name + ".jpg");
try {
byte[] bytes1 = decoder.decodeBuffer(head_photo);
output = new FileOutputStream(file);
for (int i = 0; i < bytes1.length; i++) {
output.write(bytes1[i]);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
前台解码:
public Bitmap getBitmapByByteStr(String byteStr) {
BASE64Decoder decoder = new BASE64Decoder();
Bitmap bitmap = null;
try {
byte[] result = decoder.decodeBuffer(byteStr);
bitmap = BitmapFactory.decodeByteArray(result, 0, result.length);
} catch (Exception ex) {
ex.printStackTrace();
}
return bitmap;
}