I've got the following
String urlStr = "http://example.com/my.jpg"
String mimeType = "image/jpeg";
String encoding = null;
String pageData = ""; // This is data read in from an HttpURLConnection
webview.loadDataWithBaseURL(urlStr, pageData, mimeType, encoding, urlStr);
but when I run this, all I see is a blue question mark instead of my image. What is the proper way to handle displaying an image in a WebView with loadData?
Edit:
Is there a way to do this without passing pageData as <img src="http://example.com/my.jpg/"> ? It seems silly that loadData takes a mime-type if it can only handle "text/html". Especially since the javadoc lists "image/jpeg" as an example mime-type that you might pass in.
It is possible to embedd the base64 encoded imagedata direct into the <img>-tag:
<img src="data:image/jpeg;base64,base64DataHere" />
Here an example for creating the <img>-tag (I use an byte-array instead the String for raw-data, because in my tests an String as source didn't work - I assume that String can't handle binary-data):
byte[] imageRaw = yourImage;
String image64 = Base64.encodeToString(imageRaw, Base64.DEFAULT);
String pageData = "<img src=\"data:image/jpeg;base64," + image64 + "\" />";
The Base64-class was introduced with API v.2.2 - for older API-versions you can copy the sourcefile from git and integrate it in your app. It should work with older API-versions.
Or you can use one of the alternative classes for base64-encoding like Base64Coder.
And here the complete working code for retrieving, converting and showing the image:
byte[] imageRaw = null;
try {
URL url = new URL("http://some.domain.tld/somePicture.jpg");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
out.flush();
imageRaw = out.toByteArray();
urlConnection.disconnect();
in.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String image64 = Base64.encodeToString(imageRaw, Base64.DEFAULT);
String urlStr = "http://example.com/my.jpg";
String mimeType = "text/html";
String encoding = null;
String pageData = "<img src=\"data:image/jpeg;base64," + image64 + "\" />";
WebView wv;
wv = (WebView) findViewById(R.id.webview);
wv.loadDataWithBaseURL(urlStr, pageData, mimeType, encoding, urlStr);
Use this.. solve the problem of images load in webview.
WebView webView = (WebView)findViewById(R.id.webView1);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setJavaScriptEnabled(true);
String url ="Path of image";
String imgSrcHtml = "<html><img src='" + url + "' /></html>";
webView.loadData(imgSrcHtml, "text/html", "UTF-8");
Related
What is the best way to load a jpeg from an install-time asset pack and show it on a WebView?
I got it working in case the jpeg is a regular asset, however, I couldn't get it working optimally with install-time assets:
WebView webView = this.findViewById(R.id.webView);
String sHtmlTemplate = "<img src='file:///android_asset/files/"+file+".jpg' width='100%'/>";
webView.loadDataWithBaseURL("file:///android_asset/files/", sHtmlTemplate, "text/html", "utf-8", null);
UPDATE:
The solution below works, but it is slow. Is there a way to load images directly from InputStream or install-time assets?
AssetManager assetManager = getAssets();
InputStream is = assetManager.open(songNo + ".jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024000];
int count;
while(-1 != (count = is.read(buffer, 0, buffer.length))) {
baos.write(buffer, 0, count);
}
baos.flush();
byte[] imageRaw = baos.toByteArray();
baos.close();
is.close();
String image64 = Base64.encodeToString(imageRaw, Base64.DEFAULT);
String html = String.format("<img width='100%%25' src='data:image/jpeg;base64,%s' />", image64);
webView.loadData(html, "text/html; charset=UTF-8", null);
Thanks
Perhaps the WebView is not the most optimal way to show a jpg in this case. I ended up using another control:
com.ortiz.touchview.TouchImageView touchView = this.findViewById(R.id.touchImageView);
try {
AssetManager assetManager = getAssets();
InputStream is = assetManager.open(songNo + ".jpg");
Drawable d = Drawable.createFromStream(is,"src");
touchView.setImageDrawable(d);
}catch(Exception e){
Log.i("xxx", e.getMessage());
}
I'm trying to host an Angular app with nanohttpd, so I put the files into a dist/ folder inside the assets folder of the android app. Now I want to serve the angular files but I keep getting this kind of errors in console (it only appears when trying to request fonts and images):
GET http://hostname/font.woff2 200 (OK)
This is the code that I use to serve the files:
public Response serve(IHTTPSession session) {
String filepath = getFilepath(session.getUri()); // Get filepath depending on the requested url
String mimeType = getMimeType(filepath); // Get mimetype depending on the extension of the filepath (font/woff, font/woff2, font/ttf, image/x-icon, text/html, application/javascript)
String content;
byte[] buffer;
Response res;
InputStream is;
try {
is = this.assetManager.open("dist/" + filepath);
int size = is.available();
buffer = new byte[size];
is.read(buffer);
is.close();
content = new String(buffer);
content = content.replace("old string", "new string");
if (typeText(mimeType)) { // If mimeType is text/html or application/json
res = newFixedLengthResponse(content);
}else{ // This is when I try to serve fonts or images
res = newFixedLengthResponse(Response.Status.OK, mimeType, is, size); // Not working
}
}catch(IOException e) {
res = newFixedLengthResponse("Error!");
}
return res;
}
I think that maybe the font files are getting compressed, or the size is not the real size of the InputStream. Also when loading the page, vendor.js takes a lot to download, and after that, it stops downloading the rest of the files.
I also get this error on the logcat:
Communication with the client broken, or an bug in the handler code
I fixed it like this:
public Response serve(IHTTPSession session) {
String filepath = getFilepath(session.getUri()); // Get filepath depending on the requested url
String mimeType = getMimeType(filepath); // Get mimetype depending on the extension of the filepath (font/woff, font/woff2, font/ttf, image/x-icon, text/html, application/javascript)
String content;
byte[] buffer;
Response res;
InputStream is;
try {
is = this.assetManager.open("dist/" + filepath);
if (!typeText(mimeType)) { // If mimeType is font/<something> or image/<something>
return newFixedLengthResponse(Response.Status.OK, mimeType, is, -1);
}
int size = is.available();
buffer = new byte[size];
is.read(buffer);
is.close();
content = new String(buffer);
content = content.replace("old string", "new string");
}catch(IOException e) {
content = "Error!";
}
return newFixedLengthResponse(content);
}
I really don't know what happend, but it works really well this way. It seems to me that is.available() was not returning the right file size.
I store my html page in asset folder and insert it to my sqlite.
i store my html page as text in sqlite.
Anyone know how to load my html page into webview?
i've tried to add some code, and not working
if (info.size() != 0) {
lu.setText(info.get(2));
WebView wb = (WebView) findViewById(R.id.mywebview);
wb.loadDataWithBaseURL("file:///android_asset/"+lu,"text/html","UTF-8",null);
}
You question already has well elaborated answers here on SO Webview load html from assets directory... I believe one of the answers should solve your problem... Hope that helps gudluck.
what is lu?, should it be a comma instead of +?
In any case, the method loadDataWithBaseURL takes 5 arguments:
base, data, mimetype, encoding, historyUrl
E.g:
wbHelp.loadDataWithBaseURL("file:///android_asset/",
readAssetFileAsString("index.html"),
"text/html",
"UTF-8",
null);
readAssetFileAsString is as follows:
private String readAssetFileAsString(String sourceHtmlLocation)
{
InputStream is;
try
{
is = getContext().getAssets().open(sourceHtmlLocation);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer, "UTF-8");
}
catch(IOException e)
{
e.printStackTrace();
}
return "";
}
In my project I have a files:
"MyProject/assets/folder1/image1.jpg"
"MyProject/assets/folder1/index.html".
In webView I need to open index.html (with images).
I trying this code:
String baseUrl = "file:///android_asset/folder1/";
webView.loadDataWithBaseURL(baseUrl, readFileAsString("index.html") , mimeType, "UTF-8", null);
But images don't loading.
If I put images to "assets" directory (MyProject/assets/) and make baseUrl = "file:///android_asset" images are loaded correctly;
How load images not only from root assets directory, but and from assets/folder1?
try like this
WebView webview = (WebView)this.findViewById(R.id.webview);
String html = "<html><head><title>TITLE!!!</title></head>";
html += "<body><h1>Image?</h1><img src=\"icon.png\" /></body></html>";
webview.loadDataWithBaseURL("file:///android_res/drawable/", html, "text/html", "UTF-8", null);
For more information try this link
perfect LoadDataWithBaseurl
I think you have to set the base to assets and add the sub folders to your image src's like this:
webView.loadDataWithBaseURL("file:///android_asset/", readAssetFileAsString("folder1/index.html"), "text/html", "UTF-8", null);
Html:
<img src="folder1/image1.jpg">
This worked for me on Android 5.1
private String readAssetFileAsString(String sourceHtmlLocation)
{
InputStream is;
try
{
is = getContext().getAssets().open(sourceHtmlLocation);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer, "UTF-8");
}
catch(IOException e)
{
e.printStackTrace();
}
return "";
}
try to like this
try {
String filePath = null;
filePath = "Your File path";
Bitmap bitmap = null;
bitmap = BitmapFactory.decodeFile(filePath);
Log.v("Image data-->", "" + bitmap);
imageWidth = bitmap.getWidth();
imageHeight = bitmap.getHeight();
Log.e("Width", "" + imageWidth);
filePath = "file://" + filePath;
String html = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html\";charset=utf-8\"/><title></title></head><body style=\"width:"
+ imageWidth
+ "px; height:"
+ imageHeight
+ "px; background:url("
+ filePath
+ ") no-repeat; position:relative;\">"
+ getDivTag(mapList)
+ "</body></html>";
Log.v("MIS", "" + html);
webview.getSettings().setSupportZoom(true);
webview.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
System.out.println(html);
} catch (Exception e) {
e.printStackTrace();
}
Have you give internet permission?
<uses-permission android:name="android.permission.INTERNET" />
I'm working on a project where the url sometimes can have empty spaces in it (not always) example: www.google.com/ example/test.jpg and sometimes www.google.com/example/test.jpg.
My code:
try {
URL url = new URL(stringURL);
URLConnection conexion = url.openConnection();
conexion.connect();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(fullPath.toString());
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
It's this line that fails: InputStream input = new BufferedInputStream(url.openStream(), 8192);
with a: java.io.FileNotFoundException.
I've tryed to encode the specific line but here is the kicker: the server needs the empty space " " in order to find the file, so I need to have the empty space somehow. I can find the file (jpg) if i use firefox browser.
Any help much appreciated.
Edit update:
Well now I've tryed to encode every single bit after the host part of the url to utf-8 and I've tryed using both + and %20 for blank space. Now I can manage to DL the file but it will be faulty so it can't be read.
Edit update2:
I had made a mistake with %20, that works.
Okay I solved the headache.
First I use:
completeUrl.add(URLEncoder.encode(finalSeperated[i], "UTF-8"));
For every part of the url between "/"
Then I use:
ArrayList<String> completeUrlFix = new ArrayList<String>();
StringBuilder newUrl = new StringBuilder();
for(String string : completeUrl) {
if(string.contains("+")) {
String newString = string.replace("+", "%20");
completeUrlFix.add(newString);
} else {
completeUrlFix.add(string);
}
}
for(String string : completeUrlFix) {
newUrl.append(string);
}
To build a proper urlString.
The reason this works is because http needs %20. See Trouble Percent-Encoding Spaces in Java comment by Powerlord