capture bitmap from view android [duplicate] - android

This question already has answers here:
Convert view to bitmap on Android
(9 answers)
Closed 1 year ago.
I have posted same question but it's in near to my problem that's why i have posted it second time
Hi i want to capture image from RelativeLayout, for that i have used below code
captureRelativeLayout.setDrawingCacheEnabled(true);
bitmap = captureRelativeLayout.getDrawingCache(true).copy(
Config.ARGB_8888, false);
the problem is that when i start activity and get image from that view at that time it will work fine, but if i use it second time, the image is not being refreshed, means that previous bitmap is every time i getting.
Now if i close my activity and agian start it then i will get updated image but again not in second time
:( for more information look at the
can't share image properly android

Here are two ways to convert a view to a bitmap:
Use Drawing Cache:
RelativeLayout view = (RelativeLayout)findViewById(R.id.relativelayout);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
view.setDrawingCacheEnabled(false);
I've had some issue with the drawing cache method when the view is very large (for example, a TextView in a ScrollView that goes far off the visable screen). In that case, using the next method would be better.
Use Canvas:
RelativeLayout view = (RelativeLayout)findViewById(R.id.relativelayout);
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null) {
bgDrawable.draw(canvas);
} else {
canvas.drawColor(Color.WHITE);
}
view.draw(canvas);

You should destroy the drawing cache after copying it, so the cache will be built again next time you call getDrawingCache().
The code would look like this:
captureRelativeLayout.setDrawingCacheEnabled(true);
bitmap = captureRelativeLayout.getDrawingCache(true).copy(Config.ARGB_8888, false);
captureRelativeLayout.destroyDrawingCache();
Or like this if you don't want to enable the flag:
captureRelativeLayout.buildDrawingCache(true);
bitmap = captureRelativeLayout.getDrawingCache(true).copy(Config.ARGB_8888, false);
captureRelativeLayout.destroyDrawingCache();
Reference: https://groups.google.com/d/msg/android-developers/IkRXuMtOA5w/zlP6SKlfX-0J

There is a Kotlin extension function in Android KTX:
val config: Bitmap.Config = Bitmap.Config.ARGB_8888
val bitmap = canvasView.drawToBitmap(config)

finally i got solution from this view.getDrawingCache() only works once
i just forget to put
captureRelativeLayout.setDrawingCacheEnabled(false);
i have done it by below code,
try {
if (bitmap != null) {
bitmap.recycle();
bitmap = null;
}
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
captureRelativeLayout.setDrawingCacheEnabled(true);
File sdcard = Environment.getExternalStorageDirectory();
File f = new File(sdcard, "temp.jpg");
FileOutputStream out = null;
out = new FileOutputStream(f);
captureRelativeLayout.setDrawingCacheEnabled(true);
bitmap = captureRelativeLayout.getDrawingCache(true).copy(
Config.ARGB_8888, false);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.close();
captureRelativeLayout.setDrawingCacheEnabled(false);
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f)); // imageUri
sharingIntent.setType("image/jpg");
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f)); // imageUri
startActivity(Intent.createChooser(sharingIntent, "Share Image"));
} catch (Exception e) {
e.printStackTrace();
}

As DrawingCache is depracated then in kotlin:
fun View.createBitmap(): Bitmap {
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
Canvas(bitmap).apply {
background?.draw(this) ?: this.drawColor(Color.WHITE)
draw(this)
}
return bitmap
}

view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
"bitmap" is the final bitmap..

Related

Cropping Image view

i M passing a bitmap from one activity to other, after taking the screen shot
Bitmap bitmap;
bitmap = takeScreenshot();
try {
//Write file
String filename = "bitmap.png";
FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
bitmap.recycle();
//Pop intent
Intent in1 = new Intent(this, FinalImageShare.class);
in1.putExtra("image", filename);
startActivity(in1);
} catch (Exception e) {
e.printStackTrace();
}
here i am getting the image in other activity , the problem is that the tool bar height is also coming (i m hiding the toool bar by setVisibility, )i want to crop the image so that toolbar height wont come.TIA
imageView=(ImageView)findViewById(R.id.imageView);
String filename = getIntent().getStringExtra("image");
try {
FileInputStream is = this.openFileInput(filename);
bmp = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
You can use createBitmap method, like so:
resizedbitmap = Bitmap.createBitmap(bitmap, 0, 0, yourwidth, yourheight);
Where bitmap is the bitmap you create, and resizedbitmap is the cropped one.
createBitmap() method takes as parameter in this case: bitmap, start X, start Y, width and height.
You can use those two methods to get your width and height:
bitmap.getWidth(), bitmap.getHeight()
Check also this link to learn about the createBitmap method:
Developer site
Or you can use the drawing cache property for this, like this :
View main = findViewById(R.id.view);
Bitmap screenshot;
main.setDrawingCacheEnabled(true);
screenshot = Bitmap.createBitmap(main.getDrawingCache());
main.setDrawingCacheEnabled(false);
Or similar to the last one, ctx.getWindow().getDecorView() View to get full screen bitmap cache:
View view = ctx.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
Bitmap bmap = view.getDrawingCache();
int contentViewTop = ctx.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); /* skip status bar in screenshot */
Storage.shareBitmapInfo = Bitmap.createBitmap(bmap, 0, contentViewTop, bmap.getWidth(), bmap.getHeight() - contentViewTop, null, true);
view.setDrawingCacheEnabled(false);
Hope this helps!

Save layout as an image

I have a LinearLayout and I am want to save the contents of that view as an image. I have it half working.
File imageFile;
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/a.png";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
Bitmap bitmap;
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
OutputStream fout = null;
imageFile = new File(mPath);
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 10, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
With the above code it will save a copy of the view, but only what's seen on the device screen. I have more information on the view that I want saved. The code above from here and this will only save the information seen on the screen as an image. I want all the information saved, even the information that is not on the screen (where you need to scroll to see).
How can I achieve that?
Another option is to use:
Bitmap b = Bitmap.createBitmap(width, height....)
v1.setLayoutParams // Full width and height of content
Canvas c = new Canvas(b);
v1.draw(c); // You now have full bitmap
saveBitmap(b);
Run a measure/layout pass on it and draw it to a canvas. Suppose your parent was called "view" and was a vertical LinearLayout:
view.measure(someWidth, MeasureSpec.UNSPECIFIED);
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.draw(c);

Capturing android webview image and saving to png/jpeg

I'm trying to implement the css3 page flip effect on a android/phonegap app. To do this, I need to dynamically save the current webview to png or jpeg so that it can be loaded to a div in the page flip html. I noticed the Picture class in android's docs but I'm not sure if that can be converted and saved. Could this be done through JS? Any ideas?
thanks
Try following code for capturing webview and saved jpg to sdcard.
webview.setWebViewClient(new WebViewClient() {
#Override
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( "/sdcard/" + "page.jpg" );
if ( fos != null ) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos );
fos.close();
}
}
catch( Exception e ) {
System.out.println("-----error--"+e);
}
}
});
webview.loadUrl("http://stackoverflow.com/questions/15351298/capturing-android-webview-image-and-saving-to-png-jpeg");
The easiest way (to my knowledge) to capture a View as an image is to create a new Bitmap and a new Canvas. Then, simply ask your WebView to draw itself on your own Canvas instead of the Activity's default one.
Pseudocode:
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
myWebView.draw(canvas);
//save your bitmap, do whatever you need

how to take screenshot programmatically and save it on gallery?

i would to know what is the code to take a screenshot of the current screen (after a press of a button) and save it on a gallery because I don't have a device with sd cards. So i would to save in the default gallery. thank you
Bitmap bitmap;
View v1 = findViewById(R.id.rlid);// get ur root view id
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
This should do the trick.
For saving
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg")
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
View v1 = L1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
image = (ImageView) findViewById(R.id.screenshots);
image.setBackgroundDrawable(bitmapDrawable);
For complete source code go through the below blog
http://amitandroid.blogspot.in/2013/02/android-taking-screen-shots-through-code.html
For storing the Bitmap to see the below link
Android Saving created bitmap to directory on sd card
This will save to the gallery. The code also sets an image path.. that is useful with Intent.SEND_ACTION and email Intents.
String imagePath = null;
Bitmap imageBitmap = screenShot(mAnyView);
if (imageBitmap != null) {
imagePath = MediaStore.Images.Media.insertImage(getContentResolver(), imageBitmap, "title", null);
}
public Bitmap screenShot(View view) {
if (view != null) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
return null;
}
As 323go commented, this isn't possible unless your device is rooted, really.
But if it is, it might be a good job for monkeyrunner or if you're using an emulator.

How to Save the drawing canvas in android?

I am using this API demo of the Developer site, THIS DEMO.
But i am wonder that how to save that image in to My Andrtoid Device.
Is please anyone give the Code to save that drawn image to the Android Device.
Thanks.
try this code
View content = your_view;
content.setDrawingCacheEnabled(true);
content.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Bitmap bitmap = content.getDrawingCache();
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File(path+"/image.png");
FileOutputStream ostream;
try {
file.createNewFile();
ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, ostream);
ostream.flush();
ostream.close();
Toast.makeText(getApplicationContext(), "image saved", 5000).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "error", 5000).show();
}
drawView.setDrawingCacheEnabled(true);
Bitmap bm = null;
drawView.destroyDrawingCache();
bm=drawView.getDrawingCache();
Then write the bitmap to file using bitmap factory.
One option is create another Canvas (as shown below) and repeat all your drawing on this new canvas.
Once done, call drawBitmap.
Bitmap bitmap = new Bitmap(// Set the params you like //);
Canvas canvas = new Canvas(bitmap);
// Do all your drawings here
canvas.drawBitmap(// The first picture //);
The best would be if there was a way to copy an existing canvas and then you wont need to re-draw everything but I couldn't find one.
I have implemented the below approach & worked for me.
Get your CustomView by using its id from xml file but not by instantiating the Customview.
View v = findViewById(R.id.custom_view);
//don't get customview by this way, View v = new CustomView(this);
int canvasWidth = v.getWidth();
int canvasHeight = v.getHeight();
Bitmap bitmap = Bitmap.createBitmap(canvasWidth, canvasHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
v.draw(canvas);
ImageView imageView = findViewById(R.id.image_view);
imageView.setImageBitmap(bitmap);
All code should be inside saveButton click listener.

Categories

Resources