android - 图片 - 压缩上传

图片压缩

 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;
                    }

猜你喜欢

转载自blog.csdn.net/weixin_38687303/article/details/129200689