6

我的 WebView 有一个简单的 WebViewClient 并覆盖 shouldInterceptRequest :(不是实际代码)

public class WebViewClientBook extends WebViewClient
{
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url)
    {
       File file = new File("pathToTheFile.jpeg");
       FileInputStream inputStream = new FileInputStream(file);

       return new WebResourceResponse("image/jpeg", "UTF-8", inputStream);
    }
}

由于某种原因,WebClient 无法显示图像......我相信这可能与不正确的编码有关:UTF-8。

有什么建议可以用作替代品吗?

谢谢!

4

2 回答 2

2

你这样做是不对的。您有两种方法可以做到这一点,这取决于接收该图像的内容。

案例 1:您想要返回一个字节数组。在这种情况下,您应该使用 Javascript 对其进行处理并将其解析为字符串,并将其分配给 webView 上标签的 src 字段。

    File imagefile = new File(otherPath);
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(imagefile);
        finall = fis;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    Bitmap bi = BitmapFactory.decodeStream(fis);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //PNG OR THE FORMAT YOU WANT
    bi.compress(Bitmap.CompressFormat.PNG, 100, baos);

    byte[] data = baos.toByteArray();
    InputStream is = new ByteArrayInputStream(finaldata);
    return new WebResourceResponse("text/html", "UTF-8", is);   

案例 2:您解析 Activity 上的所有内容并传递完整的 html 代码,因此在 webView 中,您将使用该数据更新哪个 innerHTML 属性。

        File imagefile = new File(otherPath);
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(imagefile);
        finall = fis;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    Bitmap bi = BitmapFactory.decodeStream(fis);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //PNG OR THE FORMAT YOU WANT
    bi.compress(Bitmap.CompressFormat.PNG, 100, baos);

    byte[] data = baos.toByteArray();
    String image64 = Base64.encodeToString(data, Base64.DEFAULT);
    String customHtml = "<html><body><h1>Hello, WebView</h1>" +
            "<h2><img src=\"data:image/jpeg;base64," + image64 + "\" /></img></h2></body></html>";
        InputStream is = new ByteArrayInputStream(finaldata);
    return new WebResourceResponse("text/html", "UTF-8", is);   

如果您只想加载图像,您可以随时执行webView.loadData(String data, String mimeType, String encoding)

希望它有帮助,我刚刚得到了我的工作

于 2014-02-18T22:44:10.073 回答
0

我有一个类似的问题,设置两个标志解决了我的问题:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
     getSettings().setAllowFileAccessFromFileURLs(true);
     getSettings().setAllowUniversalAccessFromFileURLs(true);
}
于 2013-12-23T15:24:27.473 回答