2012-12-10 22 views
6

我有我的WebView簡單WebViewClient和我重寫shouldInterceptRequest: (而不是實際的代碼)Android的Web客戶端,通過WebResourceResponse返回一個圖像資源 - 不顯示圖像

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

出於某種原因,Web客戶端是無法以顯示圖像...我相信這可能與一個不正確的編碼有關:UTF-8。

任何建議可以使用什麼作爲替代?

謝謝!

回答

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:您解析的一切活動,並通過完整的HTML代碼,以便在web視圖,你將有一個其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)

希望它能幫助的形象,我只是得到了我這個

工作
0

我也有類似的問題,設定兩個標誌解決了我的問題:

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