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

本文介绍了Android中如何以二进制形式上传和接收图片。首先,通过BitmapFactory获取图片并压缩成二进制,然后使用Base64编码传输。后台接收到Base64字符串后解码并保存为文件。同样,前台也能解码Base64字符串得到原始Bitmap。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本篇文章中图片的上传是通过二进制的形式进行传输,在前台首先获取图片的二进制形式,再通过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;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值