如何检查图像大小小于100kb android

我试图从图库中获取图像并在ImageView上设置它,听到我很好,并在ImageView上设置图像,但现在我想检查kb中所选图像的图像大小,所以我设置了图像上传的validation。 请有人建议我如何检查选择的图像尺寸是否小于100kb ?,听到我的图像选择和设置它的代码。

选择图像使用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(); } } 

要知道尺寸小于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

获取文件大小为

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

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

  ArrayList filePaths = new ArrayList<>(); ArrayList 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不为null,则在filePaths添加所有图像路径。 您也可以将此代码用于文件的文档类型。

只需从intent输入URI并获取任何文件的大小

 uri = data.getData(); Cursor returnCursor = getContentResolver().query(uri, null, null, null, null); int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE); returnCursor.moveToFirst(); Log.e("TAG", "Name:" + returnCursor.getString(nameIndex)); Log.e("TAG","Size: "+Long.toString(returnCursor.getLong(sizeIndex))); 

它将以字节为单位给出大小,因此100kb将为100000bytes。 我想这会对你有所帮助。