How to load images from internal storage in webview in android? - android

We want to display html page with its contents like text, images etc offline(without internet connection) in webview. We are able to display text only. For image, we are storing image on internal storage(sd card) from image url and replacing that image url(server url) with the image internal storage(sd card) path.
But, those images are not displaying in webview.
For example,
Below is the img tag in html..
<img alt="img" class="center_top_img" src="http://test.com/uploads/section/images/523.jpg" />
We are replacing above image url(server url) with the image internal storage(sd card) path like
<img alt="img" class="center_top_img" src=\"file:///data/data/com.app.test/files/523.jpg\" />

Wherever the image is, just get its absolute path and add "file://" in advance.
File file = ...
String imagePath + "file://" + file.getAbsolutePath();
String html = "...<img src=\""+ imagePath + "\">...";

Try this
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", "");

Remember you image is inside app directory.
You can use this:
<img src="file:///data/data/com.yourapp/files/yourimage.jpg" />

In my case I wanted the images to be in 'internal storage', not the sd-card as you stated in description (and also inferred from your usage of getExternalStorageDirectory - your question title however mentioned 'internal storage'. For this reason, get the right path:
//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();
}
Next, use this path but also ensure that it has 3 forward slashes, not 2. For me, I just copied the XPATH address from LOG.i and pasted it in my Html page directly:
<img src="file:///"+imagePSPPath +" alt="PSP Photo">

Related

Load images using html <img> tag from Android expansion file

I am trying to load my HTML files from Android expansion file(.obb) using WebView like
String prompt = "";
WebView webview = (WebView) rootView.findViewById(R.id.webview);
try {
InputStream html = getAssetFileDescriptor("www/" + mResult.getTitle() + ".html")
.createInputStream();
byte[] b = new byte[html.available()];
html.read(b);
prompt = new String(b);
html.close();
} catch (IOException e) {
Log.e("Webview", "Couldn't open webpage");
}
webview.loadData(prompt, "text/html", "utf-8");
*getAssetFileDescriptor returns InputStream read by ZipResourceFile function(Zip file library)
It loads HTML into Webview successfully but all the images inside the HTML are not appearing.
I guess It's because it cannot access to image files through img tags.
for example, my html files have img tags like
<img src="./image1.jpg" />
Relative path seems not working because html and image files are zipped into obb file.
How can I fix it?
You can mount the OBB file using StorageManager:
StorageManager storageManager = (StorageManager)app.getSystemService(Context.STORAGE_SERVICE);
boolean queued = storageManager.mountObb(<path>, null, new OnObbStateChangeListsner() {...});
Then, you can use this path to construct a path to your files: the returned path is the root to your OBB:
storageManager.getMountedObbPath(...) + "/image1.jpg";
an use that path to load your image
<img src="your_path" />

show page in webview when no internet

I need to save page from webview then open it in webview. I found method saveWebArchive and wrote code:
Timestamp tm = new Timestamp(new Date().getTime());
String fileName = String.format("web_file_%d.mht",tm.getTime());
String path = dir.toString() + File.separator + fileName;
view.getWebView().saveWebArchive(path);
then I load page where model.getContentPath() is path from code above
webView.loadUrl("file:///"+model.getContentPath());
and I got page without CSS styels etc...
Can you say how to save and load page which will be looks like original from web?

How to Open an xhtml file in Android webview

I'm developing an epub reader. I was able to extract the files from the epub and create a filetree in the device sdcard. However, when I try to read the .xhtml file. It is not working. I tried opening an html file instead and it works.
Here's my code for loading the .xhtml
webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new ReaderWebClient());
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAllowFileAccess(true);
webView.loadUrl("file:///" + Environment.getExternalStorageDirectory() + "/epub/EPUB/cover.xhtml");
I just used a hardcoded for the url first as to try if it can load the page.
The webview just displays, "Webpage not available"
Am I doing something wrong? Thanks for any help
My solution for this is I get the data for each item (.xhtml file) and pass it as an argument to loadDataWithBaseUrl(). I just have to determine the correct path for the files so that the images and CSS can be loaded correctly.
String baseUrl = "file:///" + Environment.getExternalStorageDirectory() + "/epub" + bookFilename + "/OPS/";
String data = new String(bookReader.book.getContents().get(2).getData());
webView.loadDataWithBaseURL(baseUrl, data, "application/xhtml+xml", "utf-8", null);
Use this:
webView.loadUrl("file://" + Environment.getExternalStorageDirectory().getAbsolutePath() + "epub/EPUB/cover.xhtml");
and take permission for writing to storage in manifest file, like this:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Try this:
webView.loadUrl("file://" + Environment.getExternalStorageDirectory().getAbsolutePath() + "epub/EPUB/cover.xhtml");
This is my working code .Try it.
if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.HONEYCOMB)
{
getSettings().setAllowContentAccess(true);
}
getSettings().setJavaScriptEnabled(true);
getSettings().setLayoutAlgorithm(LayoutAlgorithm.NORMAL);
getSettings().setAllowFileAccess(true);
if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.JELLY_BEAN)
{
getSettings().setAllowUniversalAccessFromFileURLs(true);
}
loadUrl("file://"+Environment.getExternalStorageDirectory()+"/epub/EPUB/cover.xhtml");
once cross check your file path.

Retrieve image path from assets folder

I have issue to retrieve image path from assets folder.
I have an image folder in assets folder. Within the folder i have three different folders.
Here is the code that i used:
String IntroImage1= "" + languageSelected + "/" + Intro1ImagePath + ".png" ;
try{
AssetManager mngr =getAssets();
InputStream BulletImgInput = mngr.open(IntroImage1);
//InputStream BulletImgInput = mngr.open("image/Malay/bullet.png");
Bitmap bitmapBullet = BitmapFactory.decodeStream(BulletImgInput);
BulletImage.setImageBitmap(bitmapBullet);
}catch(final IOException e){
e.printStackTrace();
}
I am wondering why can't i display the image? Because I have try to retrieve it through this code:
InputStream BulletImgInput = mngr.open("image/Malay/bullet.png");
It did retrieve the file, but with the string that i replaced in mngr.open it doesn't show up.
Really need you guys to help up.Thanks.
You don't need the AssetManager. You can do
BitmapFactory.decodeFile("file:///android_asset/image/Malay/bullet.jpg")
Though storing Images in the Assets is not the best way to go. You will not be able to take advantage of the Android resource management system. So unless you have a compelling reason to do this, I'd suggest that you take a look at using the res folder and the resources system.
Update: Explanation
The BitmapFactory has a method to decode a file via the decodeFile method. That's point one. Android lets you access a file in the assets folder via the file:///android_asset/{path} path. In your case, the Image at /image/Malay/bullet.jpg is the assets folder can be accessed via the the file:///android_asset/image/Malay/bullet.jpg.
Try this:
try {
// get input stream
InputStream ims = getAssets().open("avatar.jpg");
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
// set image to ImageView
mImage.setImageDrawable(d);
}
catch(IOException ex) {
Log.e("I/O ERROR","Failed when ..."
}
your BulletImage
String url = "file:///android_asset/NewFile.txt";
String url = "file:///android_asset/logo.png";
you can access any file....
InputStream BulletImgInput = mngr.open("file:///android_asset/image/Malay/bullet.png");
Maybe this could work for u.
May be problem is in missed image part of path?
String IntroImage1= "image/" + languageSelected + "/" + Intro1ImagePath + ".png" ;
instead of
String IntroImage1= "" + languageSelected + "/" + Intro1ImagePath + ".png" ;
Upd: Check values of languageSelected and Intro1ImagePath also.

How do i reference an Image from with in an HTML page locally package in an android App?

I was trying to display a static html page in an android app having some images in it.
I saved the image in assests folder and also in res/raw folder.
I was loading html file with this technique and html file is also in res/raw folder.
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
String data = ResourceUtils.loadResToString(R.raw.temp, this);
final String mimetype = "text/html";
final String encoding = "UTF-8";
mWebView.loadData(data, mimetype, encoding);
I tried different ways to refer to image like.
img1.png, /img1.png, file:///img1.png, content://img1.png
HtmlViewer/assets/img1.png, content:///HtmlViewer/assets/img1.png and file:///HtmlViewer/assets/img1.png
PackageName/assets/img1.png, content:///PackageName/assets/img1.png and file:///PackageName/assets/img1.png
Can anyone tell me how to get path for image?
file:///android_asset/file_name.ext
This should work. Use this method instead.
loadDataWithBaseURL("file:///android_asset/", summary, "text/html", "utf-8", null);

Categories

Resources