webview加载图片

版权声明:欢迎大家留言讨论 https://blog.csdn.net/u014733374/article/details/51206755

Android4.4WebView无法正常加载富文本图片的问题

image

html的富文本如下
<!DOCTYPE html>
" <html>
<head>
<meta charset=\"UTF-8\">
<title></title>
</head>
<body style=\"margin: 0;\">
<h2><span style=\"background-color:#FF9900;\"><br /></span>
<span style=\"font-size:24px;background-color:#FF9900;\">上门服务费用:100.00元。</span>
</h2><p><span style=\"font-size:24px;background-color:#FF9900;\">
<img src=\"http://device.nather.com.cn:8000/Storage/master/gallery/201604/20160411152908_3867.jpg\" style=\"width:100%;\" alt=\"\" /><br /></span> </p></body>
<html>;

原因是因为webview的JS加载不是异步进行的。加载方式如下:`@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

    mWebView= (WebView) findViewById(R.id.wb);

    WebSettings settings=mWebView.getSettings();
    settings.setJavaScriptEnabled(true);

    mWebView.loadDataWithBaseURL("",htmlStr,"text/html","UTF-8","");
}`

解决方案,通过截取webview的url加载,自己处理图片的加载显示`mWebView.setWebViewClient(new WebViewClient() {

        //重写shouldInterceptRequest
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {

            WebResourceResponse response=null;

            if(url.contains(".jpg")){
                Bitmap bitmap=ImageLoader.getInstance().loadImageSync(url);
                Log.e("wj",bitmap.toString());
                if(null!=bitmap){
                    //图片转为输入流
                    InputStream is=BitmapToIn(bitmap);
                    response=new WebResourceResponse("image/png","UTF-8",is);
                }
            }
            return response;
        }
    });`

其中图片转流的方法` private InputStream BitmapToIn(Bitmap bitmap){
InputStream is=null;
try{
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100,outputStream);

        is=new ByteArrayInputStream(outputStream.toByteArray());

        outputStream.close();
    }catch (Exception e){
        e.printStackTrace();
    }

    return is;
}`

这个问题也不是一定会出现,在webview加载图片遇到的时候这样处理就可以。

猜你喜欢

转载自blog.csdn.net/u014733374/article/details/51206755