在上传之前,我该如何压缩图片大小?

时间:2019-10-30 08:02:19

标签: android wordpress wordpress-rest-api

如何在上传之前压缩图像大小,这是我的代码     我想先压缩图片大小,然后再上传到WordPress网站     我在我的Android应用中使用WordPress rest API 我如何在上传之前压缩图像大小,这是我的代码     我想先压缩图片大小,然后再上传到WordPress网站     我在Android应用中使用WordPress rest API

// getting images selected from gallery for post and sending them to server
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // super.onActivityResult(requestCode, resultCode, data);
            switch (requestCode) {
                case FilePickerConst.REQUEST_CODE_PHOTO:
                    if (resultCode == Activity.RESULT_OK && data != null) {
                        imagePaths = new ArrayList<>();
                        imageRequestCount = 1;
                        imagePaths.addAll(data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_MEDIA));
                        if (SettingsMain.isConnectingToInternet(context)) {
                            if (imagePaths.size() > 0) {
                                btnSelectPix.setEnabled(false);
                                AsyncImageTask asyncImageTask = new AsyncImageTask();
                                asyncImageTask.execute(imagePaths);
                            }
                        }
                    } else {
                        btnSelectPix.setEnabled(true);
                        Toast.makeText(context, settingsMain.getAlertDialogMessage("internetMessage"), Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }

        private void adforest_uploadImages(List<MultipartBody.Part> parts) {
            Log.d("info image parts", parts.toString());
            String ad_id = Integer.toString(addId);
            RequestBody adID =
                    RequestBody.create(
                            okhttp3.MultipartBody.FORM, ad_id);
            Log.d("info SendImage", addId + "");
            final Call<ResponseBody> req = restService.postUploadImage(adID, parts, UrlController.UploadImageAddHeaders(context));

            req.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                    if (response.isSuccessful()) {

                        Log.v("info Upload", response.toString());
                        JSONObject responseobj = null;
                        try {
                            responseobj = new JSONObject(response.body().string());
                            Log.d("info UploadImage object", "" + responseobj.getJSONObject("data").toString());
                            if (responseobj.getBoolean("success")) {

                                adforest_updateImages(responseobj.getJSONObject("data"));

                                int selectedImageSize = imagePaths.size();
                                int totalSize = currentSize + selectedImageSize;
                                Log.d("info image2", "muImage" + totalSize + "imagePaths" + totalUploadedImages);
                                if (totalSize == totalUploadedImages) {
                                    adforest_UploadSuccessImage();
                                    imagePaths.clear();
                                    paths.clear();
                                    if (allFile.size() > 0) {
                                        for (File file : allFile) {
                                            if (file.exists()) {
                                                if (file.delete()) {
                                                    Log.d("file Deleted :", file.getPath());
                                                } else {
                                                    Log.d("file not Deleted :", file.getPath());
                                                }
                                            }
                                        }
                                    }
                                }

                            } else {
                                adforest_UploadFailedImage();
                                Toast.makeText(context, responseobj.get("message").toString(), Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            adforest_UploadFailedImage();
                            e.printStackTrace();
                        } catch (IOException e) {
                            adforest_UploadFailedImage();
                            e.printStackTrace();
                        }

                        btnSelectPix.setEnabled(true);

                    } else {
                        adforest_UploadFailedImage();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    Log.e("info Upload Image Err:", t.toString());

                    if (t instanceof TimeoutException) {
                        adforest_UploadFailedImage();

    //                    adforest_requestForImages();
                    }
                    if (t instanceof SocketTimeoutException) {
                        adforest_UploadFailedImage();
    //                    adforest_requestForImages();
    //
                    } else {
                        adforest_UploadFailedImage();
    //                    adforest_requestForImages();
                    }
                }
            });

        }

        private void adforest_UploadFailedImage() {
            progress_bar.setVisibility(View.GONE);
            loadingLayout.setVisibility(View.GONE);
            Gallary.setVisibility(View.VISIBLE);
            Gallary.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_check_circle_black_24dp, 0, 0, 0);
            Gallary.setText("" + 0);
            Gallary.setTextColor(Color.parseColor("#a0a0a0"));
            tv_done.setVisibility(View.VISIBLE);
            tv_done.setTextColor(Color.parseColor("#ff0000"));
            tv_done.setText(progressModel.getFailMessage());
            btnSelectPix.setEnabled(true);
            Toast.makeText(context, progressModel.getFailMessage(), Toast.LENGTH_SHORT).show();

        }

        private void adforest_UploadSuccessImage() {
            progress_bar.setVisibility(View.GONE);
            Gallary.setVisibility(View.VISIBLE);
            loadingLayout.setVisibility(View.GONE);
            Gallary.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_check_circle_green_24dp, 0, 0, 0);
            Gallary.setText(totalFiles + "");
            tv_done.setText(progressModel.getSuccessMessage());
            Toast.makeText(context, progressModel.getSuccessMessage(), Toast.LENGTH_SHORT).show();
            btnSelectPix.setEnabled(true);
            tv_done.setTextColor(Color.parseColor("#20a406"));
        }

        private MultipartBody.Part adforestst_prepareFilePart(String fileName, Uri fileUri) {

            File finalFile = new File(SettingsMain.getRealPathFromURI(context, fileUri));
            allFile.add(finalFile);
            // create RequestBody instance from file
            RequestBody requestFile =
                    RequestBody.create(
                            MediaType.parse(getContentResolver().getType(fileUri)),
                            finalFile
                    );
            // MultipartBody.Part is used to send also the actual file name
            return MultipartBody.Part.createFormData(fileName, finalFile.getName(), requestFile);
        }

        private File adforest_rotateImage(String path) {
            File file = null;
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            ExifInterface ei = null;
            try {
                ei = new ExifInterface(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
            int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_UNDEFINED);

            Bitmap rotatedBitmap = null;
            switch (orientation) {

                case ExifInterface.ORIENTATION_ROTATE_90:
                    rotatedBitmap = rotateImage(bitmap, 90);
                    break;

                case ExifInterface.ORIENTATION_ROTATE_180:
                    rotatedBitmap = rotateImage(bitmap, 180);
                    break;

                case ExifInterface.ORIENTATION_ROTATE_270:
                    rotatedBitmap = rotateImage(bitmap, 270);
                    break;

                case ExifInterface.ORIENTATION_NORMAL:
                default:
                    rotatedBitmap = bitmap;
            }
            file = new File(getRealPathFromURI(getImageUri(rotatedBitmap)));
            allFile.add(file);
            return file;
        }

        public Uri getImageUri(Bitmap inImage) {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            String path = MediaStore.Images.Media.insertImage(getContentResolver(), inImage, "Title", null);
            return Uri.parse(path);
        }

        public String getRealPathFromURI(Uri uri) {
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            return cursor.getString(idx);
        }


    private class AsyncImageTask extends AsyncTask<ArrayList<String>, Void, List<MultipartBody.Part>> {
            ArrayList<String> imaagesLis = null;
            boolean checkDimensions = true, checkImageSize;

            @SafeVarargs
            @Override
            protected final List<MultipartBody.Part> doInBackground(ArrayList<String>... params) {
                List<MultipartBody.Part> parts = null;
                imaagesLis = params[0];
                totalFiles = imaagesLis.size();
                for (int i = 0; i < imaagesLis.size(); i++) {
                    parts = new ArrayList<>();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
                    String currentDateandTime = sdf.format(new Date());
                    Log.d("info image", currentDateandTime);
                    checkDimensions = true;
                    checkImageSize = true;
                    if (adPostImageModel.getDim_is_show()) {
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inJustDecodeBounds = true;
                        BitmapFactory.decodeFile(imaagesLis.get(i), options);
                        int imageWidth = options.outWidth;
                        int imageHeight = options.outHeight;
                        if (imageHeight > Integer.parseInt(adPostImageModel.getDim_height()) &&
                                imageWidth > Integer.parseInt(adPostImageModel.getDim_width())) {
                            checkDimensions = true;
                        } else {
                            checkDimensions = false;
                            runOnUiThread(() -> Toast.makeText(context, adPostImageModel.getDim_height_message(), Toast.LENGTH_SHORT).show());
                        }
                    }

                    File file = new File(imaagesLis.get(i));
                    long fileSizeInBytes = file.length();
                    Integer fileSizeBytes = Math.round(fileSizeInBytes);
                    if (fileSizeBytes > Integer.parseInt(adPostImageModel.getImg_size())) {
                        checkImageSize = false;
                        runOnUiThread(() -> Toast.makeText(context, adPostImageModel.getImg_message(), Toast.LENGTH_SHORT).show());
                    } else {
                        checkImageSize = true;
                    }
                    if (checkImageSize && checkDimensions) {
                        File finalFile1 = adforest_rotateImage(imaagesLis.get(i));
    //                    File finalFile1 =new File(imaagesLis.get(i));

                        Uri tempUri = SettingsMain.decodeFile(context, finalFile1);

                        parts.add(adforestst_prepareFilePart("file" + i, tempUri));
                        adforest_uploadImages(parts);

                    }
                }
                return parts;
            }

2 个答案:

答案 0 :(得分:0)

您可以使用此按比例缩小功能

public static Bitmap scaleDown(Bitmap your_image, float YOUR_SIZE,boolean filter) { //filter false = Pixelated, true = Smooth

        float ratio = Math.min( YOUR_SIZE/ your_image.getWidth(),
                YOUR_SIZE/ your_image.getHeight());
        int width = Math.round( ratio * your_image.getWidth());
        int height = Math.round( ratio * your_image.getHeight());

        Bitmap newBitmap = Bitmap.createScaledBitmap(your_image, width, height,
                filter);
        return newBitmap;
    }

答案 1 :(得分:0)

您已经具有用于压缩代码的机制:

inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

请参阅文档: https://developer.android.com/reference/android/graphics/Bitmap.html#public-methods_1

基本上,您需要将100更改为较小的数字才能压缩图像。