How can I programmatically take a screenshot of a webview, capturing the full page?
Try this one
import java.io.FileOutputStream;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.os.Bundle;
import android.view.Menu;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
WebView w;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
w = new WebView(this);
w.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
Picture picture = view.capturePicture();
Bitmap b = Bitmap.createBitmap(picture.getWidth(),
picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
picture.draw(c);
FileOutputStream fos = null;
try {
fos = new FileOutputStream("mnt/sdcard/yahoo.jpg");
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
}
} catch (Exception e) {
}
}
});
setContentView(w);
w.loadUrl("http://search.yahoo.com/search?p=android");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Add INTERNET PERMISSION and WRITE_EXTERNAL_STORAGE in AndroidManifest.xml file.
Need to ask permission at run time for file write if app is running on or above Marshmallow.
webview.capturePicture() is deprecated, use below way can do:
Bitmap bitmap = Bitmap.createBitmap(webview.getWidth(), webview.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
webview.draw(canvas);
return bitmap;
@avinash thakur codes actually works, you just forget to mention to add
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
at Android Manifest file, otherwise, android wont allow your stream to write data / file on device.
cheers.