您的位置:首页 > 移动开发 > Android开发

Android中图片 的上传和接收以及后台图片的上传和接收

2016-12-21 09:58 465 查看
本篇文章中图片的上传是通过二进制的形式进行传输,在前台首先获取图片的二进制形式,再通过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;

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: