【问题标题】:Getting size of an image(in kb or mb) selected from gallery programatically以编程方式从图库中获取图像的大小(以 kb 或 mb 为单位)
【发布时间】:2014-09-11 21:48:39
【问题描述】:

我正在从图库中选择图像。我想以编程方式确定图像的大小(以 kb 或 mb 为单位)。 这是我写的:

public String calculateFileSize(Uri filepath)
{
    //String filepathstr=filepath.toString();
    File file = new File(filepath.getPath());

    // Get length of file in bytes
    long fileSizeInBytes = file.length();
    // Convert the bytes to Kilobytes (1 KB = 1024 Bytes)
    long fileSizeInKB = fileSizeInBytes / 1024;
    // Convert the KB to MegaBytes (1 MB = 1024 KBytes)
    long fileSizeInMB = fileSizeInKB / 1024;

    String calString=Long.toString(fileSizeInMB);
    return calString;
}

从图库中选择图像时的 uri 非常完美。但 fileSizeInBytes 的值为零。我在从图库中选择图像后在 onActivityResult 上调用此方法。我看到了一些相同的问题以前在这里。但没有一个对我有用。任何解决方案?

【问题讨论】:

    标签: android file uri android-gallery filesize


    【解决方案1】:

    试试这个,它会在新的 android 和旧版本的 uri 中返回给你的文件

    fun getFileFromUri(uri: Uri): File? {
    if (uri.path == null) {
        return null
    }
    var realPath = String()
    val databaseUri: Uri
    val selection: String?
    val selectionArgs: Array<String>?
    if (uri.path!!.contains("/document/image:")) {
        databaseUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        selection = "_id=?"
        selectionArgs = arrayOf(DocumentsContract.getDocumentId(uri).split(":")[1])
    } else {
        databaseUri = uri
        selection = null
        selectionArgs = null
    }
    try {
        val column = "_data"
        val projection = arrayOf(column)
        val cursor = context.contentResolver.query(
            databaseUri,
            projection,
            selection,
            selectionArgs,
            null
        )
        cursor?.let {
            if (it.moveToFirst()) {
                val columnIndex = cursor.getColumnIndexOrThrow(column)
                realPath = cursor.getString(columnIndex)
            }
            cursor.close()
        }
    } catch (e: Exception) {
        Log.i("GetFileUri Exception:", e.message ?: "")
    }
    val path = if (realPath.isNotEmpty()) realPath else {
        when {
            uri.path!!.contains("/document/raw:") -> uri.path!!.replace(
                "/document/raw:",
                ""
            )
            uri.path!!.contains("/document/primary:") -> uri.path!!.replace(
                "/document/primary:",
                "/storage/emulated/0/"
            )
            else -> return null
        }
    }
    return File(path)}
    

    之后你可以使用它来获取文件大小

    val file = getFileFromUri(your_uri)
    val file_size = Integer.parseInt(String.valueOf(file.length()/1024))
    

    【讨论】:

      【解决方案2】:
      private boolean validImageSize() {
              try {
                  if (bitmapPhoto!=null){
                      ByteArrayOutputStream stream = new ByteArrayOutputStream();
                      bitmapPhoto.compress(Bitmap.CompressFormat.PNG, 100, stream);
                      byte[] imageInByte = stream.toByteArray();
      
      
                      // Get length of file in bytes
                      float imageSizeInBytes = imageInByte.length;
                      // Convert the bytes to Kilobytes (1 KB = 1024 Bytes)
                      float imageSizeInKB = imageSizeInBytes / 1024;
                      // Convert the KB to MegaBytes (1 MB = 1024 KBytes)
                      float imageSizeInMB = imageSizeInKB / 1024;
                      return imageSizeInMB <= 1;
                  }else {
                      return true;
                  }
              }catch (Exception e){
                  e.printStackTrace();
                  return true;
      
              }
      
          }
      

      【讨论】:

        【解决方案3】:

        使用uri.getLastPathSegment() 而不是uri.getPath()

        public static float getImageSize(Uri uri) {
        
            File file = new File(uri.getLastPathSegment());
            return file.length(); // returns size in bytes
        }
        

        重要

        以上代码仅适用于您从图库中挑选的图片;并且不适用于文件管理器中的那些,因为它无法识别 URI 的方案

        以下方法适用于任何一种情况

        public static float getImageSize(Context context, Uri uri) {
            Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
            if (cursor != null) {
                int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
                cursor.moveToFirst();
                float imageSize = cursor.getLong(sizeIndex);
                cursor.close();
                return imageSize; // returns size in bytes
            }
            return 0;
        }
        

        从字节变为千字节 >>> /1024f

        将字节转换为 Mbytes >>> /(1024f * 1024f)

        【讨论】:

        【解决方案4】:

        这是一种计算从图库中选择的图像大小的方法。您可以在 onActivityResult 中传递您从意图中获得的 Uri:

        public static double getImageSizeFromUriInMegaByte(Context context, Uri uri) {
            String scheme = uri.getScheme();
            double dataSize = 0;
            if (scheme.equals(ContentResolver.SCHEME_CONTENT)) {
                try {
                    InputStream fileInputStream = context.getContentResolver().openInputStream(uri);
                    if (fileInputStream != null) {
                        dataSize = fileInputStream.available();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (scheme.equals(ContentResolver.SCHEME_FILE)) {
                String path = uri.getPath();
                File file = null;
                try {
                    file = new File(path);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (file != null) {
                    dataSize = file.length();
                }
            }
            return dataSize / (1024 * 1024);
        }
        

        【讨论】:

          【解决方案5】:

          试试这个,它会为你工作

          private void getImageSize(Uri choosen) throws IOException {
                  Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), choosen);
          
                  ByteArrayOutputStream stream = new ByteArrayOutputStream();
                  bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                  byte[] imageInByte = stream.toByteArray();
                  long lengthbmp = imageInByte.length;
          
                  Toast.makeText(getApplicationContext(),Long.toString(lengthbmp),Toast.LENGTH_SHORT).show();
          
              }
          

          结果

           @Override
              protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                  switch(requestCode) {
                      case SELECT_PHOTO:
                          if(resultCode == RESULT_OK){
                              Uri selectedImage = data.getData();
          
                              if(selectedImage !=null){
          
                                  img.setImageURI(selectedImage);
          
                                  try {
                                      getImageSize(choosenPhoto);
                                  } catch (IOException e) {
                                      e.printStackTrace();
                                  }
                                  //txt1.setText("Initial size: " +getImageSize(choosenPhoto)+ " Kb");
                              }
                          }
                  }
              }
          

          【讨论】:

            【解决方案6】:

            改变

            public String calculateFileSize(Uri filepath)
            {
              //String filepathstr=filepath.toString();
              File file = new File(filepath.getPath());
            
              long fileSizeInKB = fileSizeInBytes / 1024;
              // Convert the KB to MegaBytes (1 MB = 1024 KBytes)
              long fileSizeInMB = fileSizeInKB / 1024;
            
              String calString=Long.toString(fileSizeInMB);
            

            public String calculateFileSize(String filepath)
            {
              //String filepathstr=filepath.toString();
              File file = new File(filepath);
            
              float fileSizeInKB = fileSizeInBytes / 1024;
              // Convert the KB to MegaBytes (1 MB = 1024 KBytes)
              float fileSizeInMB = fileSizeInKB / 1024;
            
              String calString=Float.toString(fileSizeInMB);
            

            当您使用long 时,它会截断. 之后的所有数字因此如果您的大小小于1MB,您将得到0。

            所以请改用float 代替long

            【讨论】:

            • 感谢您的回复。不工作。fileSizeInBytes 的值返回 0.0.... uri 是 /external/images/media/1243
            • 那是一个路径而不是Uri。检查fromFile 看看Uri 的样子
            • 那我怎样才能从 imagepath 中获取大小?有可能吗??
            • 检查编辑的答案。您需要更改您的论点以及创建File 的方式
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-04-20
            • 2014-02-19
            • 2014-06-12
            • 2011-09-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多