2

I'm new to this forum, so please bear with me and gently point out mistakes if any, So I'm working on a project where I'm uploading images to server, now I want to limit the size of images, I'm giving an option to "Click image" where my code will open default camera intent and clicks the pic, or "Choose from gallery". My question is regarding "Click image", Now when user clicks an image, can I preset the image max size which can be clicked?

madsDevTeam
  • 56
  • 1
  • 7

2 Answers2

1

You can resize your image in onActivityResult method,try following code snippet

 public static Bitmap handleSamplingAndRotationBitmap(Context context, Uri selectedImage)
            throws IOException {
        int MAX_HEIGHT = 1024;
        int MAX_WIDTH = 1024;
        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        InputStream imageStream = context.getContentResolver().openInputStream(selectedImage);
        BitmapFactory.decodeStream(imageStream, null, options);
        imageStream.close();
        options.inSampleSize = calculateInSampleSizes(options, MAX_WIDTH, MAX_HEIGHT);
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        imageStream = context.getContentResolver().openInputStream(selectedImage);
        Bitmap img = BitmapFactory.decodeStream(imageStream, null, options);
        img = rotateImageIfRequired(context, img, selectedImage);
        return img;
    }

    private static int calculateInSampleSizes(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;

            // This offers some additional logic in case the image has a strange
            // aspect ratio. For example, a panorama may have a much larger
            // width than height. In these cases the total pixels might still
            // end up being too large to fit comfortably in memory, so we should
            // be more aggressive with sample down the image (=larger inSampleSize).

            final float totalPixels = width * height;

            // Anything more than 2x the requested pixels we'll sample down further
            final float totalReqPixelsCap = reqWidth * reqHeight * 2;

            while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
                inSampleSize++;
            }
        }
        return inSampleSize;
    }
    private static Bitmap rotateImageIfRequired(Context context, Bitmap img, Uri selectedImage) throws IOException {

        InputStream input = context.getContentResolver().openInputStream(selectedImage);
        ExifInterface ei;
        if (Build.VERSION.SDK_INT > 23)
            ei = new ExifInterface(input);
        else
            ei = new ExifInterface(selectedImage.getPath());

        int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                return rotateImage(img, 90);
            case ExifInterface.ORIENTATION_ROTATE_180:
                return rotateImage(img, 180);
            case ExifInterface.ORIENTATION_ROTATE_270:
                return rotateImage(img, 270);
            default:
                return img;
        }
    }
    private static Bitmap rotateImage(Bitmap img, int degree) {
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
        img.recycle();
        return rotatedImg;
    }

you just need invoke handleSamplingAndRotationBitmap method,you'll get a Bitmap which size can be set by yourself. PS: Case some pictures captured by sumsung's phone 's rotation is incorrect,so we need handle picture's orientation too,hope that can help you.

aolphn
  • 2,950
  • 2
  • 21
  • 30
0

You can simply get the size of the file. You need to store the image when u take for it. after that u can get size using below code segment

String imagePath = Environment.getExternalStorageDirectory() + "/yourImagefile.png";
File imageFile = new File(imagePath );
long filelength = imageFile .length();
length = filelength/1024;

this length give you size in KB. then you can add if condition like below

 if(length>sizeyouwant){
    //delete image and toast message with info
    if(imageFile.exists()) {
       imageFile.delete();
    }
    Toast.makeText(getApplicationContext(),
    "Image is not saved due to image size exceeds limit....",
    Toast.LENGTH_SHORT).show();
  }
PushpikaWan
  • 2,437
  • 3
  • 14
  • 23
  • This will check the file size, but I want to limit the size of jpg file while capturing the photo. If camera like oneplus or samsung note, in which image size is 4-5 MB then, user will keep taking pics using my camera and oversize images will not get accepted, that will be infinite loop. – madsDevTeam Nov 03 '18 at 04:24
  • 1
    I have no idea about check size while capturing. I think it is hard. But you can reduce size after captured or you can set a lower resolution for camera but it coudln't give any promise to that ur file is not exceed certain limt. – PushpikaWan Nov 03 '18 at 04:28
  • After taking image compress the bitmap and save again. – Abhay Koradiya Nov 03 '18 at 04:29
  • https://stackoverflow.com/questions/37299490/android-reduce-file-size-for-camera-captured-image-to-be-less-than-500-kb if you want this link will help you to get an idea about resizing image after take @madsDevTeam – PushpikaWan Nov 03 '18 at 04:30