简体   繁体   中英

how i can limit size image selected

My problem's the consumption memory, I need limit size the image selected.

Edit

I don't need to resize image after load, I can resize image using

Bitmap.createScaledBitmap(image, (int) 80, (int) 80, true);

I need to prevent user select images > 5 MB

my code

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
      if (requestCode == SELECT_PICTURE) {
        Uri selectedImageUri = data.getData();

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

      }
    }
}

Limit size folder not it's the better option.

SOLUTION

I solved my problem with this method:

public boolean MaxSizeImage(String imagePath) {
    boolean temp = false;
    File file = new File(imagePath);
    long length = file.length();

    if (length < 1500000) // 1.5 mb
        temp = true;

    return temp;
}

if you need imagePath, you can use this method

 public String getImagePath(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));
     cursor.close();

     return path;
 }

If you care about memory consumption, I think you can use Fresco image library developed by Facebook. In its docs you would find:

Fresco is a powerful system for displaying images in Android applications. It takes care of image loading and display so you don't have to.

Fresco's image pipeline will load images from the network, local storage, or local resources. To save data and CPU, it has three levels of cache; two in memory and another in internal storage .

Fresco's Drawees show a placeholder for you until the image has loaded and automatically show to the image when it arrives. When the image goes off-screen, it automatically releases its memory.

Then in Features section you would found:

Memory

A decompressed image - an Android Bitmap - takes up a lot of memory. This leads to more frequent runs of the Java garbage collector. This slows apps down. The problem is especially bad without the improvements to the garbage collector made in Android 5.0.

On Android 4.x and lower, Fresco puts images in a special region of Android memory. It also makes sure that images are automatically released from memory when they're no longer shown on screen. This lets your application run faster - and suffer fewer crashes.

Apps using Fresco can run even on low-end devices without having to constantly struggle to keep their image memory footprint under control.

Official site: http://frescolib.org/

GitHub: https://github.com/facebook/fresco

Article: Introducing Fresco: A new image library for Android

It seems to be fitted to your needs. That's why I need to write an answer about it.

Hope it help

use something like this to load the image at the memory youd like it to be, this is using a file path, there is methods for streams also check out BitmapFactory

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

helper method

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

You could try using Picasso to fetch images. There's a resize option when you call and get images, that could help with size. You'd probably be limited to "one size fits all" for images though. It also makes a lot of additional features simple when loading images, such as placeholders, error images when your image doesn't load, and a few other utilities.

Here's an example request from the link:

Picasso.with(context)
  .load(url)
  .resize(50, 50)
  .centerCrop()
  .into(imageView)

Try This Hackro :D

First:

public static final int PICK_IMAGE = 1;
private void takePictureFromGalleryOrAnyOtherFolder() 
{
 Intent intent = new Intent();
 intent.setType("image/*");
 intent.setAction(Intent.ACTION_GET_CONTENT);
 startActivityForResult(Intent.createChooser(intent, "Select Picture"),PICK_IMAGE);
}

Then:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
           if (requestCode == PICK_IMAGE) {
                Uri selectedImageUri = data.getData();
                String imagePath = getRealPathFromURI(selectedImageUri);
               //Now you have imagePath do whatever you want to do now
             }//end of inner if
         }//end of outer if
  }

public String getRealPathFromURI(String contentURI) {
    Uri contentUri = Uri.parse(contentURI);

    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = null;
    try {
        if (Build.VERSION.SDK_INT > 19) {
            // Will return "image:x*"
            String wholeID = DocumentsContract.getDocumentId(contentUri);
            // Split at colon, use second item in the array
            String id = wholeID.split(":")[1];
            // where id is equal to
            String sel = MediaStore.Images.Media._ID + "=?";

            cursor = context.getContentResolver().query(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    projection, sel, new String[] { id }, null);
        } else {
            cursor = context.getContentResolver().query(contentUri,
                    projection, null, null, null);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    String path = null;
    try {
        int column_index = cursor
                .getColumnIndex(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        path = cursor.getString(column_index).toString();
        cursor.close();
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
    return path;
}

I don't know how to do that while selecting an image, but you can check size of file after select image.

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
        Uri selectedImageUri = data.getData();
        String imagepath = getPath(selectedImageUri);
        Bitmap bitmap=BitmapFactory.decodeFile(imagepath);

        int sizeInBytes = 0;
        int MAX_BYTES = your_number_of_bytes;

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1) {
                sizeInBytes = bitmap.getRowBytes() * bitmap.getHeight();
        } else {
                sizeInBytes = bitmap.getByteCount();
        }

        if(sizeInBytes > MAX_BYTES) {
                // If the image is higher than max number of bytes, start all over again.
        }

        }
    }
}

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