【问题标题】:How do I retrieve the file size of an image selected from my gallery?如何检索从我的图库中选择的图像的文件大小?
【发布时间】:2020-01-01 02:59:38
【问题描述】:

我已经尝试过所有其他帖子的答案,它们似乎都返回 0.0 作为我图像的文件大小,这不可能是真的。我认为文件路径是导致它返回不正确文件大小的原因。这是我的代码:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            imageUri = data.getData();
            textViewImageAttachmentStatus.setText("File has been attached");
            textViewImageAttachmentStatus.setTextColor(Color.parseColor("#008577"));
            Picasso.get().load(imageUri).into(imageViewPreviewImage);

            String imagePath = imageUri.getPath();
            File imageFile = new File(imagePath);
            long imageSize = imageFile.length() / 1024;
            System.out.println(imageSize);
        }
    }

【问题讨论】:

  • 你能登录 imageUri.getPath() 吗?
  • 给你朋友 - “I/System.out: /document/image:89506”
  • hmm 你可以尝试使用光标检索文件吗? ,我会分享
  • 这能回答你的问题吗? Get the size of an Android file resource?
  • @SanjayBhalani 在该问题的已接受答案中,作者提到了 R.raw.nameOfFile。如果没有,我会为“nameOfFile”传递什么?

标签: android


【解决方案1】:

更好地使用 Cursor 它的强大功能,试试这个

Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            assert cursor != null;
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            mediaPath1 = cursor.getString(columnIndex);
            cursor.close();
            File file = new File(mediaPath);
            int file_size = Integer.parseInt(String.valueOf(file.length() / 1048576));
            System.out.println(file_size);

【讨论】:

    【解决方案2】:

    你可以试试这个代码

    导入以下包

    import java.io.File;
    import java.text.DecimalFormat;
    

    需要的时候放下面的代码

    private static final DecimalFormat format = new DecimalFormat("#.##");
    private static final long MiB = 1024 * 1024;
    private static final long KiB = 1024;
    
    public static String getFileSize(File file) {
    
        if (!file.isFile()) {
            throw new IllegalArgumentException("Expected a file");
        }
        final double length = file.length();
    
        if (length > MiB) {
            return format.format(length / MiB) + " MB";
        }
        if (length > KiB) {
            return format.format(length / KiB) + " KB";
        }
        return format.format(length) + " Bytes";
    }
    

    调用上述函数

    String fileSize = getFileSize(imageFile);
    

    【讨论】:

    • 这返回了“预期的文件”。我不确定为什么。我现有的代码有问题吗?
    • @RafA 我认为你必须检查 imageUri.getPath();返回有效路径。
    【解决方案3】:

    这是从图库中选择获取文件大小的代码

     case AppConstant.REQUEST_GALLERY_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    long dataSize = 0;
                    File f = null;
                    Uri uri = data.getData();
                    String scheme = uri.getScheme();
                    System.out.println("Scheme type " + scheme);
                    if (scheme.equals(ContentResolver.SCHEME_CONTENT)) {
                        try {
                            InputStream fileInputStream = getApplicationContext().getContentResolver().openInputStream(uri);
                            dataSize = fileInputStream.available();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        Log.e("File Size Length", dataSize + ""); // Here get file sizw
                    } else if (scheme.equals(ContentResolver.SCHEME_FILE)) {
                        String path = uri.getPath();
                        try {
                            f = new File(path);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        Log.e("File Size Length", f.length() + ""); // here get file size
                    }
                }
            break;
    

    【讨论】:

    • IDE 显示“无法解析符号 AppConstant” - 有什么想法吗?我在网上找不到任何关于此的内容。
    • 我在 onActivityResult 中使用了 switch case,以便在 AppConstant 中使用静态请求代码。您在 if 中使用此代码“if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK)”
    【解决方案4】:
    Here the value is returned, for example, if you want not to upload a file larger than 5 megabytes 
    public boolean MaxSizeImage(String imagePath){
    
        long file_size = new File(imagePath).length() / 1024;//"kB"
        if (file_size <=  5000){ //5M
            return true;
        }
    
        return false;
    }
    //Here the path is fetched
    public static String getFilePath(Context context, Uri uri) {
        String imagePath;
        String[] filePath = {MediaStore.Images.Media.DATA};
        Cursor c = context.getContentResolver().query(uri, filePath, null, null, null);
        assert c != null;
        c.moveToFirst();
        int columnIndex = c.getColumnIndex(filePath[0]);
        imagePath = c.getString(columnIndex);
        c.close();
        return imagePath;
    }
    

    【讨论】:

      【解决方案5】:

      这是获取用户刚刚选择的文件大小的一种更简单、更复杂的方法。请看看这个 sn-p 是否有帮助。

      Uri returnUri = intent.getData();
      Cursor returnCursor = getContentResolver().query(returnUri, null, null, null, null);
      
      int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
      int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
      returnCursor.moveToFirst();
      String selectedFileName = returnCursor.getString(nameIndex);
      Long selectedFileSize = Long.toString(returnCursor.getLong(sizeIndex));
      

      完整的文档here,您还可以在其中找到这个用 Kotlin 编写的 sn-p。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-07
        • 1970-01-01
        • 2019-05-27
        • 2016-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多