【问题标题】:How to get the size of an image in Android?如何在Android中获取图像的大小?
【发布时间】:2012-03-08 04:30:36
【问题描述】:

我能够获取图像的高度和宽度。但是有没有一种方法可以检索存储在手机中的图像的大小(以字节或 kb 或 mb 为单位)?

【问题讨论】:

  • 文件 file=new File(Environment.getExternalStorageDirectory(), "image.file");长长度 = file.length();
  • 在此之前,您是如何获得图像的高度和宽度的?

标签: android image image-size


【解决方案1】:

假设您谈论的是位图(而不是 ImageView),则有一个方法 Bitmap.getByteCount()。

【讨论】:

【解决方案2】:

您只需要创建一个新的File 对象,例如...

String filepath = Environment.getExternalStorageDirectory() + "/file.png";
File file = new File(filepath);
long length = file.length();

【讨论】:

  • 这给出了文件的大小,而不是图像。
【解决方案3】:

感谢您的回答。这就是我最终解决它的方法:

 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; 

感谢您的时间和答案:)

【讨论】:

  • 笨蛋回答。 lengthbmp 以字节为单位。 lengthbmp/1024.0 以 KB 为单位。 lengthbmp/1024.0/1024.0 以 MB 为单位。
  • 压缩前和压缩后如何获取?
  • 压缩前可以使用bitmap.getByteCount()。请记住,“压缩”版本是 JPEG,因此如果您比较这两种尺寸,您不一定将苹果与苹果进行比较。
【解决方案4】:

当您右键单击查看文件详细信息时,这将返回在计算机中匹配的真实大小。

File file = new File("/sdcard/my_video.mp4");
long length = file.length() / 1024; // Size in KB

【讨论】:

    【解决方案5】:
     File file = new File("/sdcard/imageName.jpeg");
     long length = file.length();
     length = length/1024;
     System.out.println("File Path : " + file.getPath() + ", File size : " + length +" KB");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-24
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-09
      相关资源
      最近更新 更多