Android WebClient returning image resource via WebResourceResponse - does not display image

I have a simple WebViewClient for my WebView and I override shouldInterceptRequest: (Not valid code)

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); } } 

For some reason, WebClient cannot display the image ... I believe this may have something to do with the wrong encoding: UTF-8.

Any suggestions on what to use as an alternative?

Thanks!

+6
source share
2 answers

You are doing it wrong. You have 2 ways to do this, and it depends on what this image gets.

Case 1: you want to return an array of bytes. In this case, you should have Javascript processing it and parsing it into a string and assigning it to the src field of your tag in webView.

  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); 

Case 2: you parse all the actions and pass the full html code, so in the webView you will have some kind of innerHTML property with this data.

  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); 

If you just want to upload an image, you can always do webView.loadData(String data, String mimeType, String encoding)

Hope this helps, I just started working with this

+2
source

I had a similar problem and setting two flags solved my problems:

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { getSettings().setAllowFileAccessFromFileURLs(true); getSettings().setAllowUniversalAccessFromFileURLs(true); } 
0
source

All Articles