簡體   English   中英

如何在android的webview中從內部存儲加載圖像?

[英]How to load images from internal storage in webview in android?

我們希望在 webview 中離線(沒有互聯網連接)顯示 html 頁面及其內容,如文本、圖像等。 我們只能顯示文本。 對於圖像,我們從圖像 url 將圖像存儲在內部存儲(sd 卡)上,並用圖像內部存儲(sd 卡)路徑替換該圖像 url(服務器 url)。

但是,這些圖像沒有顯示在 webview 中。

例如,下面是html中的img標簽..

<img alt="img" class="center_top_img" src="http://test.com/uploads/section/images/523.jpg" /> 

我們正在用圖像內部存儲(sd 卡)路徑替換上面的圖像 url(服務器 url),如

<img alt="img" class="center_top_img" src=\"file:///data/data/com.app.test/files/523.jpg\" /> 

無論圖像在哪里,只需獲取其絕對路徑並提前添加“file://”即可。

File file = ...
String imagePath + "file://" + file.getAbsolutePath();
String html = "...<img src=\""+ imagePath + "\">...";

嘗試這個

mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setBuiltInZoomControls(true);
String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
String imagePath = "file://"+ base + "/test.jpg";
String html = "<html><head></head><body><img src=\""+ imagePath + "\"></body></html>";
mWebView.loadDataWithBaseURL("", html, "text/html","utf-8", "");  

請記住,您的圖像位於 app 目錄中。 你可以使用這個:

<img src="file:///data/data/com.yourapp/files/yourimage.jpg" />

在我的情況下,我希望圖像位於“內部存儲”中,而不是您在描述中所述的 sd 卡(並且還從您對 getExternalStorageDirectory 的使用中推斷出來 - 但是您的問題標題提到了“內部存儲”。因此,獲取正確的道路:

//image paths; 'images' folder was earlier created by getFilesDir
String basePATH = "";
String imagePSPPath = "";
String imagePSP = "passportImage.jpeg"; //can be generated dynamically if needed
File images = new File(getApplicationContext().getFilesDir(), "images");
if(file.exists()) {
    //fine, it exists, build right strings
    basePATH = images.toString();
    imagePSPPath = basePATH +"/"+ imagePSP;
    Log.i("XPATH", imagePSPPath);   //loged for ease of copying
}else {
   //error, path not found
    Toast.makeText(YourActivity.this, "Sorry, path not found: ", Toast.LENGTH_LONG).show();
}

接下來,使用此路徑,但還要確保它有 3 個正斜杠,而不是 2 個。 對我來說,我只是從 LOG.i 復制了 XPATH 地址並將其直接粘貼到我的 Html 頁面中:

<img src="file:///"+imagePSPPath +" alt="PSP Photo">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM