2015-03-19 97 views
1

我想从图库中获取图像并将其设置在ImageView,听到没关系我可以在ImageView上设置图像,但是现在我想检查所选图像的图像大小在kb,所以我设置图像上传验证。 任何人都可以建议我如何检查选择的图像尺寸小于100kb?, 听到是我的图像选择和设置代码。如何检查图像大小小于100kb android

选择图片期运用Intent

Intent iv = new Intent(
        Intent.ACTION_PICK, 
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 

      startActivityForResult(iv, RESULT_LOAD_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]); 
     picturePath = cursor.getString(columnIndex); 
     cursor.close(); 
     Bitmap bmp=BitmapFactory.decodeFile(picturePath); 

     ivLogo.setImageBitmap(bmp); 
      uploadNewPic(); 
    } 
} 

回答

7

知道大小小于100kb。你应该知道要比较的图像大小。有一些方法来知道位图

方法1

Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), 
     R.drawable.ic_launcher); 


Bitmap bitmap = bitmapOrg; 
ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); 
byte[] imageInByte = stream.toByteArray(); 
long lengthbmp = imageInByte.length; 

方法2

File file = new File("/sdcard/Your_file"); 
long length = file.length()/1024; // Size in KB 

的大小更多研究

http://developer.android.com/reference/android/graphics/Bitmap.html#getByteCount%28%29

+0

感谢Bro的帮助 – 2015-03-20 02:27:47

+0

在方法1中,您在压缩后没有检查文件大小,所以我感觉它错了 – 2016-11-04 07:42:19

2

获取文件大小为

File img = new File(picturePath); 
int length = img.length(); 

它会以字节为单位返回的大小。您可以将字节转换为kb

+0

感谢您的回答 – 2015-03-20 02:28:01

0
ArrayList<String> filePaths = new ArrayList<>(); 
    ArrayList<String> newFilePath = new ArrayList<>(); //for storing file path which size is less than 100 KB 

    if (imagePaths != null) { 
     filePaths.addAll(imagePaths); 
     for (int i = 0; i < filePaths.size(); i++) { 
      File file = new File(filePaths.get(i)); 
      int file_size = Integer.parseInt(String.valueOf(file.length()/1024));  //calculate size of image in KB 
      if (file_size < 100) 
       newFilePath.add(filePaths.get(i)); //if file size less than 100 KB then add to newFilePath ArrayList 
     } 
    } 

这里imagePaths存储我们选择的所有图像的路径。然后,如果imagePaths不为空,则在filePaths中添加所有图像路径。您也可以将此代码用于文件类型的文件。