以编程方式获取从图库中选择的图像大小(以kb或mb为单位)



我正在从图库中选择图像。我想以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的值是0。在从图库中选择图像后,我在onActivityResult上调用此方法。我之前在这里看到了一些同样的问题。但没有一个对我有用。有解决方案吗?

变化

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

试试这个,它会为你工作的

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

And on result

 @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");
                    }
                }
        }
    }

这是计算从图库中选择的图像大小的方法。你可以在onActivityResult:

中传递你从intent获得的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);
}

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

将bytes改为Kbytes>>/1024f

将bytes改为mb>>>/(1024f * 1024f)

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

试试这个,它会从新的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))

在最近的Android版本中,访问直接文件有许多限制。我们可以使用ContentProviders从Uri获取大小。这里引用

 fun getFileSize(uri: Uri): Long {
    val cursor: Cursor? = context.contentResolver!!.query(
        yourFileUri, null, null, null, null
    )
    cursor?.use {
        val sizeColumn =
            it.getColumnIndexOrThrow(android.provider.MediaStore.MediaColumns.SIZE)
        if (it.moveToNext()) {
            return it.getLong(sizeColumn)
        }
    }
    return 0L
 }

你也可以使用下面的函数来设置

的大小

android.text.format.Formatter。formatFileSize(背景:背景?, sizeBytes: Long): String!

最新更新