I have a view I want to create a bitmap for that view(later I want to print that bitmap). What I have tried is as follows
private Bitmap convertViewToBitMap() {
View v = rootView; //rootView is my view to be converted in bitmap
v.setDrawingCacheEnabled(true);
Bitmap b = v.getDrawingCache();
return b;
}
My view "rootview" is a expandable list, when I call convertViewToBitMap(), I get the bitmap of view which is visible on screen, but if view is expanded, the expanded part which is going out of screen does not come in bitmap. So is there a way to get a bitmap of complete view even if it is partially visible on screen?
Try this:
Make some adjustments to your view. "Measure" method defines the proper dimensions of your view (change 1000 and 600 to what suits you best)
view.measure(MeasureSpec.makeMeasureSpec(1000, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(600, MeasureSpec.EXACTLY));
Re-define your view with the new measurements (change also 0,0)
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
Create the bitmap
Bitmap bm=Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
After that, you can draw your bitmap to any view
Canvas cn=new Canvas(bm);
anyview.draw(cn);
Also, you can save the bitmap into a file
try {
FileOutputStream out = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Related
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!
I want to get the picture of the view(not ImageView) inside,but the picture I got was not clear,Of course the original picture is clear ,here is my codes
public static Bitmap getDrawBitmap(View designView){
designView.destroyDrawingCache();
designView.setDrawingCacheEnabled(true);
designView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
return designView.getDrawingCache();
}
I have tried to scale the View,and then getDrawingCache(),but it didn't work,the view's size didn't change
Bitmap bitmap=ImgUtils.getDrawBitmap(testBtn);
float w=1260f;
float h=1660f;
float x= w/(bitmap.getWidth()/DrawAttribute.density);
float y= h/(bitmap.getHeight()/DrawAttribute.density);
Log.e("x-y",x+"-"+y);
Bitmap result=Bitmap.createBitmap(1260,1660,Bitmap.Config.ARGB_8888);
Canvas offScreen = new Canvas(result);
Matrix matrix=new Matrix();
matrix.setScale(x,y);
offScreen.drawBitmap(bitmap, matrix, null);
//存储路径
OutputStream stream = null;
try {
if (LiApplication.creatDir()) {
stream = new FileOutputStream(Environment.getExternalStorageDirectory()+ "/yc/img/"
+ "save.png");
}
} catch (FileNotFoundException e) {
}
Bitmap.CompressFormat format = Bitmap.CompressFormat.PNG;
result.compress(format, 100, stream);
This is a Demo code for taking screen shot of whole View.
View v = (View) findViewById(R.id.myView);
Bitmap mybitmap = Bitmap.createBitmap(
v.getChildAt(0).getWidth(),
v.getChildAt(0).getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(mybitmap);
iv.getChildAt(0).draw(c);
//remember here View may be any view including ScrollView or what ever it may be.
saveBitmap(bitmap);
Hope this will help. Thanks
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);
Everything I tried with setDrawingCacheEnabled and getDrawingCache was not working. The system was making an image but it just looked black.
Other people on SO seemed to be having a similar problem but the answers seemed either too complicated or irrelevant to my situation. Here are some of the ones I looked at:
Save view like bitmap, I only get black screen
Screenshot shows black
getDrawingCache always returns the same Bitmap
Convert view to bitmap on Android
bitmap is not saving properly only black image
Custom view converting to bitmap returning black image
And here is my code:
view.setDrawingCacheEnabled(true);
Bitmap bitmap = view.getDrawingCache();
try {
FileOutputStream stream = new FileOutputStream(getApplicationContext().getCacheDir() + "/image.jpg");
bitmap.compress(CompressFormat.JPEG, 80, stream);
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
view.setDrawingCacheEnabled(false);
I'm sharing my answer below in case anyone else makes the same mistake I did.
My problem was that my view was a TextView. The text on the TextView was black (naturally) and in the app the background looked white. However, I later recalled reading that a view's background is by default transparent so that whatever color is below shows through.
So I added android:background="#color/white" to the layout xml for the view and it worked. When I had been viewing the image before I had been looking at black text over a black background.
See the answer by #BraisGabin for an alternate way that does not require overdrawing the UI.
I just found a good option:
final boolean cachePreviousState = view.isDrawingCacheEnabled();
final int backgroundPreviousColor = view.getDrawingCacheBackgroundColor();
view.setDrawingCacheEnabled(true);
view.setDrawingCacheBackgroundColor(0xfffafafa);
final Bitmap bitmap = view.getDrawingCache();
view.setDrawingCacheBackgroundColor(backgroundPreviousColor);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
view.setDrawingCacheEnabled(cachePreviousState);
Where 0xfffafafa is the desired background color.
Used below code to get bitmap image for view it work fine.
public Bitmap loadBitmapFromView(View v) {
DisplayMetrics dm = getResources().getDisplayMetrics();
v.measure(View.MeasureSpec.makeMeasureSpec(dm.widthPixels,
View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(dm.heightPixels,
View.MeasureSpec.EXACTLY));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap returnedBitmap =
Bitmap.createBitmap(v.getMeasuredWidth(),
v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(returnedBitmap);
v.draw(c);
return returnedBitmap;
}
Is it possible to get a full bitmap from a viewgroup-object?
This code takes a 'screenshot' off the view group that's currently on the screen, but I want the whole view, also what's not currently on the screen.
public void export(ViewGroup view){
view.setDrawingCacheEnabled(true);
view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Bitmap bitmap = view.getDrawingCache(true);
}
Here I used ScrollView to get the whole view to bitmap
so Here u can use instead of scrollview anyother view group like linerlayout etc..
Bitmap map = loadBitmapFromView(getApplicationContext(),scrollView);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
map.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//you can create a new file name "test.jpg" in sdcard folder.
File f = new File("/sdcard" +"/" + "mainemailpdf.jpg");
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
bArray = bytes.toByteArray();
// remember close de FileOutput
fo.close();
and for loadBitmapFromView method is:
public static Bitmap loadBitmapFromView(Context context, View v) {
Toast.makeText(context,
v.getMeasuredHeight() + "::::::::::::" + v.getMeasuredWidth(),
Toast.LENGTH_LONG).show();
if (v.getMeasuredHeight() > 0) {
v.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getWidth(), v.getWidth());
v.draw(c);
return b;
}
return null;
}
I hope it helps :)
Any query let me know.
It is not possible since Android system scales down the bitmap.
For ex - if your bitmap size is 480*800 then its size is 480*800*4 = 1536000.
The multiplication with 4 is because each pixel is 4 bytes - RGBA.
Meaning more than a mega and a half for every unscaled image. If the Android won't scale down image you will probably get
OutOfMemoryException after a few image loadings.
as
you have 3 options:
1) view.draw(canvas) you'll get the visible portion of the image(only what is actually being drawn to the screen)
2) getDrawingCache() - will give you the scaled down image.
3) Create custom view which saves the bitmap to the disk and loads it from there when requested