android - 图片 - 压缩上传

该代码实现从本地路径读取图片,进行压缩,然后使用OkHttpClient上传至服务器。压缩过程包括设置Bitmap的inSampleSize属性减小图片尺寸,并根据图片类型选择JPEG或PNG格式压缩。最后,通过HTTPPUT请求执行文件上传。
摘要由CSDN通过智能技术生成

图片压缩

 private byte[] bitmapToByte(String path) {
        ByteArrayOutputStream out = null;
        // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path,options);
        // 调用上面定义的方法计算inSampleSize值
        options.inSampleSize = calculateInSampleSize(options, 600, 600);
        // 使用获取到的inSampleSize值再次解析图片
        options.inJustDecodeBounds = false;
        Bitmap b = BitmapFactory.decodeFile(path,options);

        try {
            if (TextUtil.isEmpty(quality)) {
                quality = "75";
            }
            int qt = Integer.parseInt(quality);
            out = new ByteArrayOutputStream();
            if (!TextUtil.isEmpty(mImageType) && mImageType.contains("jpeg")) {
                b.compress(Bitmap.CompressFormat.JPEG, qt, out);
            } else if (!TextUtil.isEmpty(mImageType) && mImageType.contains("png")) {
                b.compress(Bitmap.CompressFormat.PNG, qt, out);
            } else {
                b.compress(Bitmap.CompressFormat.JPEG, qt, out);
            }
            out.flush();
            out.close();
            b.recycle();
            return out.toByteArray();
        } catch (IOException e) {
            Log.d(TAG, e.toString());
        } catch (Exception e) {
            Log.d(TAG, e.toString());
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new byte[]{};
    }

图片上传

                   try {
                        //上传图片
                        OkHttpClient client = new OkHttpClient().newBuilder().build();
                        RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), bitmapToByte(path));
                        Request request = new Request.Builder().url(mUploadUrl).put(requestBody).build();
                        Response response = client.newCall(request).execute();
                        if (response.isSuccessful()) {
                            return "success";
                        } else {
                            return null;
                        }
                    } catch (Exception e) {
                        Log.e(TAG, "uploadPic: " + e.getLocalizedMessage());
                        return null;
                    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凌晨三点的北京

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值