how to save images displayed in webview?
我想将webview中显示的图像保存到本地存储,并且webview应该缓存它显示的图像,如何访问缓存的图像并将它们保存到存储中?
WebView webView = new WebView(this);
//your image is in webview
Picture picture = webView.capturePicture();
Canvas canvas = new Canvas();
picture.draw(canvas);
Bitmap image = Bitmap.createBitmap(picture.getWidth(),
picture.getHeight(),Config.ARGB_8888);
canvas.drawBitmap(mimage, 0, 0, null);
if(image != null) {
ByteArrayOutputStream mByteArrayOS = new
ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 90, mByteArrayOS);
try {
fos = openFileOutput("image.jpg", MODE_WORLD_WRITEABLE);
fos.write(mByteArrayOS.toByteArray());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
尝试以上从webView捕获图像
Then you have to set a WebViewClient to your WebView and override shouldOverrideUrlLoading and onLoadResource methods. Let me give you a simple example:
WebView yourWebView; // initialize it as always...
// this is the funny part:
yourWebView.setWebViewClient(yourWebClient);
// somewhere on your code...
WebViewClient yourWebClient = new WebViewClient(){
// you tell the webclient you want to catch when a url is about to load
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
return true;
}
// here you execute an action when the URL you want is about to load
@Override
public void onLoadResource(WebView view, String url){
if( url.equals("http://cnn.com") ){
// do whatever you want
//download the image from url and save it whereever you want
}
}
}
I did used the code from above and it "worked" but it was producing black images only so after a couple of hours here are my corrections, now it writes on the external sd card with no deprecation risks or path issues...
public void captureWV() {
Picture picture = webview.capturePicture();
Bitmap image = Bitmap.createBitmap(picture.getWidth(),picture.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(image);
picture.draw(canvas);
if (image != null) {
ByteArrayOutputStream mByteArrayOS = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 90, mByteArrayOS);
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath());
File file = new File(dir, "filename.jpg");
FileOutputStream fos = new FileOutputStream(file);
fos.write(mByteArrayOS.toByteArray());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
also here is the beginning of my MainActivity
public class MainActivity extends Activity {
private static final String URL = "http://punto.gt"; //your website
WebView webview;
// your code here
}
链接地址: http://www.djcxy.com/p/10658.html
上一篇: EDE中有哪些不同的目标类型?
下一篇: 如何保存在webview中显示的图像?