【问题标题】:Difference between URI and bitmap imageURI和位图图像的区别
【发布时间】:2017-05-16 19:04:27
【问题描述】:

imageView 显示图像的最佳做法是什么?我们有两种类型的图像,一种是bitmap,另一种是URI。如果我使用位图,

Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);

图像有点模糊。

如果我使用URI,有时会出现内存不足的问题。

 URI imageUri = data.getData();
 imageView.setImageURI(imageURI);

这两者有什么区别?

【问题讨论】:

    标签: android bitmap imageview uri


    【解决方案1】:

    Bitmap 是准备好的图像 (set of bytes with color data),URI 是指向某物的路径。 URI 可以是 /emulated/home/... ,可以是 http://google.com 等等。

    【讨论】:

      【解决方案2】:

      ImageView 有 4 个 API 来指定图像。

      1. setImageDrawable(Drawable drawable)
      2. setImageBitmap(位图 bm)
      3. setImageResource(int resId)
      4. setImageURI(URI uri)

      这里的setImageDrawable 是其他API 所依赖的原始函数。其他 3 个只是帮助您编写更少代码的方法。

      setImageURIsetImageBitmap 都在 UI 线程上运行。我想说setImageBitmap 比第一个快一点。 setImageURI 真的取决于 Uri 资源的来源(例如,uri 可能指向一个甚至没有存储在手机上的远程文件)。

      setImageURI() 不适合在 UI 线程上用作读取和解码,这可能会导致延迟打嗝。

      最好使用以下内容:-

      改为setImageDrawable(android.graphics.drawable.Drawable)setImageBitmap(android.graphics.Bitmap)BitmapFactory

      您也可以从uri 返回bitmap 并在imageview 中使用它

       Uri imageUri = intent.getData();
      Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),imageUri);
      Imageview my_img_view = (Imageview ) findViewById (R.id.my_img_view);
      my_img_view.setImageBitmap(bitmap);
      

      有时在图像视图上加载大位图可能会导致内存不足异常..所以你应该有效地加载位图..

          public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
          int reqWidth, int reqHeight) {
      
          // First decode with inJustDecodeBounds=true to check dimensions
          final BitmapFactory.Options options = new BitmapFactory.Options();
          options.inJustDecodeBounds = true;
          BitmapFactory.decodeResource(res, resId, options);
      
          // Calculate inSampleSize
          options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
      
          // Decode bitmap with inSampleSize set
          options.inJustDecodeBounds = false;
          return BitmapFactory.decodeResource(res, resId, options);
      }
      
      mImageView.setImageBitmap(
          decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));
      

      也可以查看这些链接..更好地理解

      1. Strange out of memory issue while loading an image to a Bitmap object

      2. Android 开发者文档:https://developer.android.com/training/displaying-bitmaps/load-bitmap.html

      【讨论】:

      • 我怎么知道 reqWidth 和 reqHeight 的值是多少,这样图像才不会看起来模糊?
      猜你喜欢
      • 2011-11-16
      • 1970-01-01
      • 2016-05-18
      • 1970-01-01
      • 2013-06-24
      • 1970-01-01
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多