简体   繁体   中英

How do I compress image when uploading to server?

I have been trying to look at other examples for compression of images. However, I still don't know where and how do I include the codes for compression into. Could anybody help me with this?

public void uploadMultipart() {
            //getting name for the image
            String name = editText.getText().toString().trim();

        //getting the actual path of the image
        String path = getPath(filePath);


        //Uploading code
        try {
            String uploadId = UUID.randomUUID().toString();

            //Creating a multi part request
            new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
                    .addFileToUpload(path, "image") //Adding file
                    .addParameter("name", name) //Adding text parameter to the request
                    .setNotificationConfig(new UploadNotificationConfig())
                    .setMaxRetries(2)
                    .startUpload(); //Starting the upload

        } catch (Exception exc) {
            Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

 //method to get the file path from uri
    public String getPath(Uri uri) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        String document_id = cursor.getString(0);
        document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
        cursor.close();

        cursor = getContentResolver().query(
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
        cursor.moveToFirst();

        String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
//        Bitmap bmp = BitmapFactory.decodeFile(path);
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        cursor.close();


        return path;
    }

Here is the code for compress image in Bitmap

Below code for jpeg images

   Bitmap bitmap = BitmapFactory.decodeStream(getAssets().open("imagename.png"));
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); // you can set as 90 for compress ration
   Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

Below code for png images:

   Bitmap bitmap= BitmapFactory.decodeStream(getAssets().open("imagename.png"));
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
   Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

Otherwise, Here is code which encode the string and send to server as encoded format image

  String encodedString ="";
  try {

            BitmapFactory.Options options = null;
            options = new BitmapFactory.Options();
            options.inSampleSize = 1;
            bitmap = BitmapFactory.decodeFile(filepath, options);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            // Must compress the Image to reduce image size to make upload easy
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);

            byte[] byte_arr = stream.toByteArray();
            // Encode Image to String
            encodedString = Base64.encodeToString(byte_arr, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }

Try to above solution. It will work for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM