我在这段简单的代码中遇到了麻烦。我从网上下载了一张图片,并在本地保存为:
File mFile = new File(context.getFilesDir(), "a.png");
if(!mFile.exists()) { mFile.createNewFile(); }
FileOutputStream fos = new FileOutputStream(mFile);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
我试着在ImageView上显示这个图像,它正在工作。现在我尝试在WebView上显示保存的图像。
String data = "<body>" +"<img src="a.png"/></body>";
webview.loadDataWithBaseURL(getActivity().getFilesDir().toString(),data , "text/html", "utf-8",null);
不工作,webview没有显示任何内容。我尝试用png的webview,我把自己放在/assets中,它正在工作。
我认为我的语法指向字符串数据中的文件是错误的,但我不确定。
感谢您的帮助。
谢谢。Alex。
好了,在测试了很多不同的东西之后,我最终得到了这个工作代码。
WebView webview = (WebView) view.findViewById(R.id.imageView);
try {
FileInputStream in = getActivity().openFileInput("image_behindfragment.png");
BufferedInputStream buf = new BufferedInputStream(in);
byte[] bitMapA= new byte[buf.available()];
buf.read(bitMapA);
Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
//imageview.setImageBitmap(bM);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
String imgToString = Base64.encodeToString(bitMapA,Base64.DEFAULT);
String imgTag = "<img src='data:image/png;base64," + imgToString
+ "' align='left' bgcolor='ff0000'/>";
webview.getSettings().setBuiltInZoomControls(true);
webview.setInitialScale(30);
WebSettings webSettings = webview.getSettings();
webSettings.setUseWideViewPort(true);
webview.loadData(imgTag, "text/html", "utf-8");
}
} catch (Exception e) {
e.printStackTrace();
}
String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
String imagePath = "file://"+ base + "/a.png";
String html = "<html><head></head><body><img src=""+ imagePath + ""></body></html>";
WebView.loadDataWithBaseURL("file:///mnt/sdcard/Your Folder/", html, "text/html","utf-8", "");