Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android WebClient, returning an image resource through WebResourceResponse - not displaying image

I have a simple WebViewClient for my WebView and am overriding shouldInterceptRequest: (Not actual 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, the WebClient is unable to display the image... I believe it might have something to do with an incorrect encoding: UTF-8.

Any suggestions what to use as an alternative?

Thanks!

like image 928
eugene Avatar asked Dec 10 '12 19:12

eugene


1 Answers

You are doing it wrong. You have 2 ways to do it, and it depends on what is receiving that image.

Case 1: You want to return a byte array. In this case, you should have a Javascript treating it and parsing it into a string and assign it to the src field of your tag on the 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 everything on the Activity and pass the full html code so in the webView you will have a which innerHTML property will be updated 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);   

In case you just want to load the image you can always do a webView.loadData(String data, String mimeType, String encoding)

Hope it helps, I just got mine working with this

like image 147
AAlferez Avatar answered Nov 12 '22 20:11

AAlferez