eug*_*ene 6 android webview webviewclient
我有一个简单的WebViewClient用于我的WebView并且覆盖了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);
}
}
Run Code Online (Sandbox Code Playgroud)
由于某种原因,WebClient无法显示图像...我相信它可能与不正确的编码有关:UTF-8.
有什么建议可以作为替代方案吗?
谢谢!
你做错了。您有两种方法可以做到这一点,这取决于接收该图像的内容。
情况 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);
Run Code Online (Sandbox Code Playgroud)
情况 2:您解析 Activity 上的所有内容并传递完整的 html 代码,因此在 webView 中您将拥有一个将使用此数据更新的 insideHTML 属性。
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);
Run Code Online (Sandbox Code Playgroud)
如果您只想加载图像,您可以随时执行webView.loadData(String data, String mimeType, String encoding)
希望它有帮助,我刚刚开始使用这个
归档时间: |
|
查看次数: |
3821 次 |
最近记录: |