网络图片URL转化为Bitmap对象

在平时的开发中我们会经常用到网络图片的加载,有时候需要把网络图片的URL地址转换为Bitmap对象

来供我们使用:

方法如下:

1:首先我们自定义一个接口因为牵涉到网络基本上都要使用异步加载,这里先定义一个接口回调:

//自定义一个接口
public interface HttpCallBackListener {
    void onFinish(Bitmap bitmap);
    void onError(Exception e);
}

2:牵涉到图片问题我们很自然的想到图片的大小问题,如果图片太大可能导致OOM的问题:

    这里再先写一个方法来用来压缩bitmap使之符合我们的要求代码如下:

public Bitmap createBitmapThumbnail(Bitmap bitmap,boolean needRecycler){
    int width=bitmap.getWidth();
    int height=bitmap.getHeight();
    int newWidth=80;
    int newHeight=80;
    float scaleWidth=((float)newWidth)/width;
    float scaleHeight=((float)newHeight)/height;
    Matrix matrix=new Matrix();
    matrix.postScale(scaleWidth,scaleHeight);
    Bitmap newBitMap=Bitmap.createBitmap(bitmap,0,0,width,height,matrix,true);
    if(needRecycler)bitmap.recycle();
    return newBitMap;
}

3:最后也是最下面的最重要的方法了是用来解析网络图片URL地址并转换成bitmap对象

/**
 * bitmap转换
 * @param
 * @return
 */
public void getImage(final String path, final HttpCallBackListener listener) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            URL imageUrl = null;
            try {
                imageUrl = new URL(path);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            try {
                HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                InputStream is = conn.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                Bitmap bitmap1= createBitmapThumbnail(bitmap,false);
                if (listener != null) {
                    listener.onFinish(bitmap1);
                }
                is.close();
            } catch (IOException e) {
                if (listener != null) {
                    listener.onError(e);
                }
                e.printStackTrace();
            }
        }
       
    }).start();

}

4:通过这样三步就基本上可以实现解决我们的问题了。

猜你喜欢

转载自blog.csdn.net/qq_42618969/article/details/81137825
今日推荐