我正在从gallery中选择一个图像。我想用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
上调用此方法后,从图库中选择图像。我看到了以前问过同样的问题。但没有一个对我有用。有什么解决方案吗?
答案 0 :(得分:2)
更改
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
答案 1 :(得分:2)
试试这个,它会对你有用
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");
}
}
}
}
答案 2 :(得分:1)
使用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
要从字节变为兆字节>>> /(1024f * 1024f)
答案 3 :(得分:0)
这是一种计算从图库中选择的图像尺寸的方法。您可以在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);
}
答案 4 :(得分:0)
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;
}
}
答案 5 :(得分:0)
试试这个,它会从新的安卓和旧版本的 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))