Android用ImageView显示本地和网上的图片

Android用ImageView显示本地和网上的图片

使用方法

GetBitMap.getHttpBitmap(imgUrl, new GetBitMap.Callback() {
  @Override
  public void onSuccess(Bitmap bitmap) {
    imageView.setImageBitmap(bitmap);
  }
});

源码

public class GetBitMap {

  public static Bitmap getLoacalBitmap(String url) {
    try {
      FileInputStream fis = new FileInputStream(url);
      return BitmapFactory.decodeStream(fis);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      return null;
    }
  }

  public static void getHttpBitmap(String url,Callback callback) {
    @SuppressLint("HandlerLeak") Handler handler = new Handler(){
      @Override
      public void handleMessage(@NonNull Message msg) {
        super.handleMessage(msg);
        callback.onSuccess((Bitmap) msg.obj);
      }
    };
    new Thread(new Runnable() {
      @Override
      public void run() {
        URL myFileUrl = null;
        Bitmap bitmap = null;
        try {
          Log.d(TAG, url);
          myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
          e.printStackTrace();
        }
        try {
          HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
          conn.setConnectTimeout(3000);
          conn.setDoInput(true);
          conn.connect();
          InputStream is = conn.getInputStream();
          bitmap = BitmapFactory.decodeStream(is);
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
        Message message = new Message();
        message.obj = bitmap;
        handler.sendMessage(message);
      }
    }).start();
  }

  public interface Callback{
    void onSuccess(Bitmap bitmap);
  }
}

参考连接

Android用ImageView显示本地和网上的图片

原文地址:https://www.cnblogs.com/guhunjun/p/android-imgview.html