Question

I have a question regarding scaling down the selected image in image gallery so i can upload it to a server via php.

So the order of action are:

1)Get selected image from gallery (DONE)

2)Scale it down and compress it to jpg (Got stucked here)

3)Upload to server async(DONE)

I need to connect 1st and 3rd step.So far i have done this:

GET SELECTED IMAGE:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            Bitmap yourSelectedImage = BitmapFactory.decodeFile(picturePath); 

            new async_upload().execute(picturePath.toString());
        }

    }

ASYNC UPLOAD IT:

public class async_upload extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... arg0) {
            uploadFile(arg0[0]);
            return "asd";
        }

        @Override       
        protected void onPostExecute(String result) {

        }
    } 

     public int uploadFile(String sourceFileUri) {
..............Code for uploading works.......
}

And my function for scaling down the image.

private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {

        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o);

        // The new size we want to scale to
        final int REQUIRED_SIZE = 640;

        // Find the correct scale value. It should be the power of 2.
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp / 2 < REQUIRED_SIZE
               || height_tmp / 2 < REQUIRED_SIZE) {
                break;
            }
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);

    }

As you can see i am sending the URI of the selected image to uploadFile to be uploaded async. My problem is how can i "make a copy" of the selected image,compress/scale and send this image instead of the original one. Of course i dont want to alter the user's images...but send a scaled version.

Any ideas? Thank you!

Was it helpful?

Solution

you can do something along these lines

File pngDir = new   File(Environment.getExternalStorageDirectory(),"PicUploadTemp");
               if (!pngDir.exists()) {
            pngDir.mkdirs();
            }
             pngfile = new File(pngDir,"texture1.jpg");

             FileOutputStream fOut;
            try {
                    fOut = new FileOutputStream(pngfile);
                     finalbitmap.compress(Bitmap.CompressFormat.JPG, 100,fOut);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            pngUri = Uri.fromFile(pngfile);

for the code you put up first add this method to your class

public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        // Calculate ratios of height and width to requested height and width
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will guarantee
        // a final image with both dimensions larger than or equal to the
        // requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }

    return inSampleSize;
    }

then in your code that you just put up, do it like this

BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(picturePath, options);
                int imageHeight = options.outHeight;
                int imageWidth = options.outWidth;
                String imageType = options.outMimeType;
                    options.inSampleSize = calculateInSampleSize(options,512,256);//512 and 256 whatever you want as scale
                    options.inJustDecodeBounds = false;
                Bitmap yourSelectedImage = BitmapFactory.decodeFile(selectedImagePath,options);
//Bitmap yourSelectedImage = BitmapFactory.decodeFile(picturePath);

            File pngDir = new   File(Environment.getExternalStorageDirectory(),"PicUploadTemp");
            if (!pngDir.exists()) {
            pngDir.mkdirs();
         }

          File pngfile = new File(pngDir,"texture1.jpg");
            FileOutputStream fOut;

            try {
                    fOut = new FileOutputStream(pngfile);

                     yourSelectedImage.compress(Bitmap.CompressFormat.JPEG, 50,fOut);


            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            new async_upload().execute(pngfile.getPath().toString());
            yourSelectedImage.recycle();
            resizedBitmap.recycle();
            Log.d("INTERNET", yourSelectedImage.toString());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top