• 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显示本地和网上的图片

  • 相关阅读:
    SpringBoot之Banner介绍
    SpringBoot事件监听机制
    SpringBoot 启动流程图
    ApplicationContextInitializer的理解和使用
    SpringFactoriesLoader解析
    计时器之StopWatch
    ftp上下载文件
    打印两个函数的返回值
    关闭所有已打开的文件和关闭应用
    TypeError: include() got an unexpected keyword argument 'app_name'
  • 原文地址:https://www.cnblogs.com/guhunjun/p/android-imgview.html
Copyright © 2020-2023  润新知