Drawing offscreen WebView to bitmap - android

I am trying to capture a image of a webview drawn off screen to the user in android and i always end up with a black image. It is the correct size and everything just not the
Here is the code I am using:
String theURL = "file:///android_asset/www/pages/page2.html";
WebView webview = new WebView(ctx);
webview.loadUrl(theURL);
Bitmap bm = Bitmap.createBitmap(1000, 1000, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bm);
webview.draw(c);
OutputStream stream = null;
try {
stream = new FileOutputStream(Environment.getExternalStorageDirectory() +"/page.jpg");
bm.compress(CompressFormat.JPEG, 80, stream);
if (stream != null) stream.close();
return new PluginResult(PluginResult.Status.OK);
} catch (IOException e) {
return new PluginResult(PluginResult.Status.ERROR, e.toString());
} finally {
bm.recycle();
}
Thanks if anyone can help.

The webview.loadUrl(theURL); starts the loading of the page, that can take a while. Wait before drawing your webview until after the page is loaded. You can use a setWebViewClient(WebViewClient client) to set up an object to receive notice when the page has finished loading.

Related

webview not generating completely as bitmap in lollipop android

I want to generate bitmap from webview full page.
some codes
Below code for generating Bitmap from webview
Webview to Bitmap :
Picture p = webview.capturePicture();
webview.setDrawingCacheEnabled(true);
webview.buildDrawingCache();
final PictureDrawable pictureDrawable = new PictureDrawable(pict);
Bitmap bitmap = null;
try
{
bitmap = Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth(),pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888);
}
catch (OutOfMemoryError e)
{
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
Canvas canvas = new Canvas(bitmap);
canvas.drawPicture(pictureDrawable.getPicture());
webview.setDrawingCacheEnabled(false);
below code for to save the file in memory for that
To save as file :
if(bitmap!=null)
{
File myDir = new File(Environment.getExternalStorageDirectory(), "AackAack");
if (myDir.exists())
{
}
else
{
myDir.mkdir();
}
String fname = System.currentTimeMillis() + ".png";
file1 = new File(myDir, fname);
try
{
FileOutputStream out = new FileOutputStream(file1);
result.compress(Bitmap.CompressFormat.PNG, 10, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
here webview loading fine but not generating as bitmap completely in lollipop.
this problem is getting only in lollipop devices. and same code when runs on kitkat then its working fine..
how can i resolve this issue? please help me..
Thanks in advance..
You need to call WebView.enableSlowWholeDocumentDraw() before creating any WebViews. That is, if you have any WebViews in your layout, make sure you call this method before calling setContentView() in your onCreate() shown below.
if (Build.VERSION.SDK_INT >= 21) {
webview.enableSlowWholeDocumentDraw ();
}
and its worked fine for me..
Thanks

How to take a screenshot of Android's Surface View?

I want to programatically take screen shot of my game, just as you'd get in Eclipse DDMS.
Screenshot taken through the solution proposed here: How to programmatically take a screenshot in Android? and in most other SO questions only have View elements visible, but not the SurfaceView.
SCREENSHOTS_LOCATIONS = Environment.getExternalStorageDirectory().toString() + "/screenshots/";
// Get root view
View view = activity.getWindow().getDecorView().getRootView();
// Create the bitmap to use to draw the screenshot
final Bitmap bitmap = Bitmap.createBitmap(screenWidth, screenHeight, Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(bitmap);
// Get current theme to know which background to use
final Theme theme = activity.getTheme();
final TypedArray ta = theme
.obtainStyledAttributes(new int[] { android.R.attr.windowBackground });
final int res = ta.getResourceId(0, 0);
final Drawable background = activity.getResources().getDrawable(res);
// Draw background
background.draw(canvas);
// Draw views
view.draw(canvas);
// Save the screenshot to the file system
FileOutputStream fos = null;
try {
final File sddir = new File(SCREENSHOTS_LOCATIONS);
if (!sddir.exists()) {
sddir.mkdirs();
}
fos = new FileOutputStream(SCREENSHOTS_LOCATIONS
+ System.currentTimeMillis() + ".jpg");
if (fos != null) {
if (!bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos)) {
Log.d("ScreenShot", "Compress/Write failed");
}
fos.flush();
fos.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Any help in this regard would be highly appreciated. Thanks.
I hope this also useful for you. here little difference for the above answer is
for I used glsurfaceview to take the screen shots hen i click the button.
this image is stored in sdcard for mentioned folder :
sdcard/emulated/0/printerscreenshots/image/...images
My Program :
View view_storelayout ;
view_storelayout = findViewById(R.id.gl_surface_view);
button onclick() {
view_storelayout.setDrawingCacheEnabled(true);
view_storelayout.buildDrawingCache(true);
Bitmap bmp = Bitmap.createBitmap(view_storelayout.getDrawingCache());
view_storelayout.setDrawingCacheEnabled(false); // clear drawing cache
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 90, bos);
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream fis = new ByteArrayInputStream(bitmapdata);
final Calendar c=Calendar.getInstance();
long mytimestamp=c.getTimeInMillis();
String timeStamp=String.valueOf(mytimestamp);
String myfile="hari"+timeStamp+".jpeg";
dir_image=new File(Environment.getExternalStorageDirectory()+
File.separator+"printerscreenshots"+File.separator+"image");
dir_image.mkdirs();
try {
File tmpFile = new File(dir_image,myfile);
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "myPath:"
+dir_image.toString(), Toast.LENGTH_SHORT).show();
Log.v("hari", "screenshots:"+dir_image.toString());
}
Note :
But, here i am faced one problem. In this surfaceview , i drawn line and circle
at runtime. after drawn some objects, when i take screenshots , its stored only for
black image like surfaceview is stored as an image.
And also i want to store that surfaceview image as an .dxf format(autocad format).
i tried to stored image file as an .dxf file format.its saved successfully in
autocad format. but, it cant open in autocad software to edit my .dxf file.
The code from the Usman Kurd answer will not work is most cases.
Unless you're rendering H.264 video frames in software with Canvas onto a View, the drawing-cache approach won't work (see e.g. this answer).
You cannot read pixels from the Surface part of the SurfaceView. The basic problem is that a Surface is a queue of buffers with a producer-consumer interface, and your app is on the producer side. The consumer, usually the system compositor (SurfaceFlinger), is able to capture a screen shot because it's on the other end of the pipe.
Take Screenshot of SurfaceView

lazyload image in appwidget

Is there a way to lazyload an image from the internet into a remoteview.
remoteView.setImageViewBitmap(R.id.image, UrlUtils.loadBitmap(bitmapUrl));
I use this function but it is blocking my widget during a small time.
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(getPageInputStream(url));
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream);
Utils.copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
// options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
options);
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
Thanks
Absolutely
Draw your widget the usual way, all the textual parts, etc. beside image
Create a service which will load image. Here's good tutorial that includes how to create and call service from the appwidget
After updating your widget call the service. Pass widget ID and image URL
Load image from cache or remotely in your service and update your widget again. Voila, you have it now
Try android-query lib for lazyload loading.
https://code.google.com/p/android-query/#Image_Loading

Screenshot of a webpage with Flash elements

I would like to take a screenshot of a page displayed in a WebView. The page contains flash elements - and here is the problem. When I take a screenshot all the flash parts of the page are blank.
I am using this piece of code to take a screenshot:
WebView webView = (WebView) findViewById(R.id.webview);
Picture picture = webView.capturePicture();
Bitmap screenshot = Bitmap.createBitmap(picture.getWidth(),
picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(screenshot);
picture.draw(c);
File file = new File("/sdcard/screenshot.jpg");
FileOutputStream ostream = null;
try {
file.createNewFile();
ostream = new FileOutputStream(file);
screenshot.compress(CompressFormat.JPEG, 90, ostream);
Log.d("Test", "Screenshot taken");
} catch (Exception e) {
Log.e("Test", "Error", e);
} finally {
try {
ostream.close();
} catch (IOException ignore) {
}
}
I was also trying to acquire Bitmap of the screen contents using the solution given in this SO question:
View webView = findViewById(R.id.webview);
Bitmap bitmap = webView.getDrawingCache();
This also doesn't work - the result is the same (i.e. blank flash elements).
So the question is: How to take a screenshot of WebView contents also with flash elements?

Saving the the image from webview to some folder

I used Google chart api to generate the chart using webview in android. Now my next requirement is to save that image into some local storage and to send the image via email and mms.please help me in doing that.
thanks
nishant
WebView w = new WebView(this);
//Loads the url
w.loadUrl("http://www.yahoo.com";);
//After loading completely, take its picture
Picture picture = w.capturePicture();
//Create a new canvas
Canvas mCanvas = new Canvas();
//Draw the Picture into the Canvas
picture.draw(mCanvas);
//Create a Bitmap
Bitmap sreenshot = Bitmap.createBitmap(picture.getWidth(),
picture.getHeight(),Config.ARGB_8888);
//copy the content fron Canvas to Bitmap
mCanvas.drawBitmap(mBitmapScreenshot, 0, 0, null);
//Save the Bitmap to local filesystem
if(sreenshot != null) {
ByteArrayOutputStream mByteArrayOpStream = new
ByteArrayOutputStream();
screenshot.compress(Bitmap.CompressFormat.JPEG, 90,
mByteArrayOpStream);
try {
fos = openFileOutput("yahoo.jpg",
MODE_WORLD_WRITEABLE);
fos.write(mByteArrayOpStream.toByteArray());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
And for sending the images thro email u can go thru this question
and for MMS

Categories

Resources