How to use setImageUri() on Android

后端 未结 7 1453
误落风尘
误落风尘 2020-12-03 21:01

Can you help me please? I\'ve tried :

ImageButton imgbt=(ImageButton)findViewById(R.id.imgbutton);
Uri imgUri=Uri.parse(\"/data/data/MYFOLDER/myimage.png\");         


        
相关标签:
7条回答
  • 2020-12-03 21:24

    Its best to avoid building the path by hand, try :

    imgbt.setImageUri(Uri.fromFile(new File("/data/data/....")));
    
    0 讨论(0)
  • 2020-12-03 21:26

    ImageView.setImageUri only works for local Uri, ie a reference to a local disk file, not a URL to an image on the network.

    Here is an example of how to fetch a Bitmap from the network.

        private Bitmap getImageBitmap(String url) {
            Bitmap bm = null;
            try {
                URL aURL = new URL(url);
                URLConnection conn = aURL.openConnection();
                conn.connect();
                InputStream is = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                bm = BitmapFactory.decodeStream(bis);
                bis.close();
                is.close();
           } catch (IOException e) {
               Log.e(TAG, "Error getting bitmap", e);
           }
           return bm;
        } 
    

    Once you have the Bitmap from getImageBitmap(), use: imgView.setImageBitmap(bm);

    0 讨论(0)
  • 2020-12-03 21:27

    It should be

    Uri imgUri=Uri.parse("file:///data/data/MYFOLDER/myimage.png");

    0 讨论(0)
  • 2020-12-03 21:29

    I also met this issue, it did not show anything. I saw something like this in android developer. It didn't use setImageURI.

    private Bitmap getBitmapFromUri(Uri uri, Context context) throws IOException {
        ParcelFileDescriptor parcelFileDescriptor =
                context.getContentResolver().openFileDescriptor(uri, "r");
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
        parcelFileDescriptor.close();
        return image;
    }
    

    Just for your reference.

    0 讨论(0)
  • 2020-12-03 21:37

    I solved it with framework. Added this line into the gradle:

    implementation 'com.facebook.fresco:fresco:1.8.0'
    

    Init singlton in application-class(or another main class in your app)

    Fresco.initialize(applicationContext)
    

    And in finish, use it.

    XML:

     <com.facebook.drawee.view.SimpleDraweeView
      android:id="@+id/avatar"
      android:layout_width="110dp"
      android:layout_height="110dp" /> 
    

    Java:

    avatar.setImageURI(user.getAvatarUrl())
    
    0 讨论(0)
  • 2020-12-03 21:43

    How about this one:

    Bitmap bitmap = BitmapFactory.decodeFile(fullFileName);
    imgProfileImage.setImageBitmap(bitmap);
    
    0 讨论(0)
提交回复
热议问题