【发布时间】:2019-11-12 15:56:04
【问题描述】:
我想在 webview 中使用我的课程下载 HTML 格式的图像。 怎么做? 我在 baseurl 中的网页加载。 我的班级从互联网下载图像。 请举例说明 谢谢
【问题讨论】:
我想在 webview 中使用我的课程下载 HTML 格式的图像。 怎么做? 我在 baseurl 中的网页加载。 我的班级从互联网下载图像。 请举例说明 谢谢
【问题讨论】:
使用这个:webviewId.loadDataWithBaseURL("", response,
"text/html", "UTF-8", "");
或
Html.ImageGetter() use this, this will search <img> tag
http://developer.android.com/reference/android/text/Html.ImageGetter.html
示例链接:
【讨论】:
public class ImageGetter implements Html.ImageGetter {
Context c;
View container;
public ImageGetter(View t, Context c) {
this.c = c;
this.container = t;
}
public Drawable getDrawable(String source) {
URLDrawable urlDrawable = new URLDrawable();
// get the actual source
ImageGetterAsyncTask asyncTask =
new ImageGetterAsyncTask( urlDrawable);
asyncTask.execute(source);
// return reference to URLDrawable where I will change with actual image from
// the src tag
return urlDrawable;
}
public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
URLDrawable urlDrawable;
public ImageGetterAsyncTask(URLDrawable d) {
this.urlDrawable = d;
}
@Override
protected Drawable doInBackground(String... params) {
String source = params[0];
return fetchDrawable(source);
}
@Override
protected void onPostExecute(Drawable result) {
// set the correct bound according to the result from HTTP call
urlDrawable.setBounds(0, 0, 0 + result.getIntrinsicWidth(), 0
+ result.getIntrinsicHeight());
// change the reference of the current drawable to the result
// from the HTTP call
urlDrawable.drawable = result;
// redraw the image by invalidating the container
ImageGetter.this.container.invalidate();
}
public Drawable fetchDrawable(String urlString) {
try {
//Get image from online and save it to the storage.
InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");
drawable.setBounds(0, 0, 0 + drawable.getIntrinsicWidth(), 0
+ drawable.getIntrinsicHeight());
Bitmap bm = BitmapFactory.decodeStream( is);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file = new File(extStorageDirectory, urlString+".PNG");
FileOutputStream outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
return drawable;
} catch (Exception e) {
// offline use the stored image
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
Bitmap bitmap = BitmapFactory.decodeFile(extStorageDirectory+urlString+".PNG");
Drawable drawable = new BitmapDrawable(bitmap);
drawable.setBounds(0, 0, 0 + drawable.getIntrinsicWidth(), 0
+ drawable.getIntrinsicHeight());
return drawable;
}
}
private InputStream fetch(String urlString) throws IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
return response.getEntity().getContent();
}
}
}
【讨论】: