美文网首页
将网络图片 转化成bitmap

将网络图片 转化成bitmap

作者: zhengLH | 来源:发表于2018-09-10 12:20 被阅读3次

    【1】解析图片 在 子线程, 解析完成 使用Handler 通知到主线程。

     /**
     * 根据 图片URL 转换成 Bitmap
     * @param url
     * @return
     */
    public static Bitmap returnBitMap(final String url, final android.os.Handler handler){
    
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL imageurl = null;
    
                try {
                    imageurl = new URL(url);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    HttpURLConnection conn = (HttpURLConnection)imageurl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
    
                    Message message = handler.obtainMessage();
                    message.obj = bitmap;
                    message.arg1 = 1;
                    handler.sendMessage(message);
    
                    is.close();
    
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    
        return bitmap;
    }
    

    【2】 使用

            ImageUtil.returnBitMap(picUrl, new Handler(Looper.getMainLooper()){
    
                @Override
                public void handleMessage(Message msg) {
                      super.handleMessage(msg);
                     
                    // todo 具体逻辑
                    Bitmap mBitmap = (Bitmap) msg.obj;
                    int width = mBitmap.getWidth();
                    int height = mBitmap.getHeight();
                    final float picScale = (float) width/height;   // 宽高比
    
        
                }
            });

    相关文章

      网友评论

          本文标题:将网络图片 转化成bitmap

          本文链接:https://www.haomeiwen.com/subject/srcsgftx.html