Convert view to bitmap on Android - android

I need to convert a view to a bitmap to preview my view and to save it as an image. I tried using the following code, but it creates a blank image. I cannot understand where I made a mistake.
View viewToBeConverted; Bitmap viewBitmap = Bitmap.createBitmap(viewToBeConverted.getWidth(), viewToBeConverted.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(viewBitmap);
viewToBeConverted.draw(canvas);
savephoto(“f1”, viewBitmap);
//// public void savephoto(String filename,Bitmap bit)
{
File newFile = new File(Environment.getExternalStorageDirectory() + Picture_Card/"+ filename+ ".PNG");
try
{
newFile.createNewFile();
try
{
FileOutputStream pdfFile = new FileOutputStream(newFile); Bitmap bm = bit; ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG,100, baos); byte[] bytes = baos.toByteArray();
pdfFile.write(bytes);
pdfFile.close();
}
catch (FileNotFoundException e)
{ //
}
} catch (IOException e)
{ //
}
}

here is my solution:
public static Bitmap getBitmapFromView(View view) {
//Define a bitmap with the same size as the view
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
//Bind a canvas to it
Canvas canvas = new Canvas(returnedBitmap);
//Get the view's background
Drawable bgDrawable =view.getBackground();
if (bgDrawable!=null)
//has background drawable, then draw it on the canvas
bgDrawable.draw(canvas);
else
//does not have background drawable, then draw white background on the canvas
canvas.drawColor(Color.WHITE);
// draw the view on the canvas
view.draw(canvas);
//return the bitmap
return returnedBitmap;
}
Enjoy :)

The most voted solution did not work for me because my view is a ViewGroup(have been inflated from a LayoutInflater). I needed to call view.measure to force the view size to be calculated in order to get the correct view size with view.getMeasuredWidth(Height).
public static Bitmap getBitmapFromView(View view) {
view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.draw(canvas);
return bitmap;
}

use new kotlin extention function view.drawToBitmap()
mLayout.drawToBitmap()

Here is extension in Kotlin inspired by : Google Android Maps Utils Icon Generator
fun View.convertToBitmap(): Bitmap {
val measureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
measure(measureSpec, measureSpec)
layout(0, 0, measuredWidth, measuredHeight)
val r = Bitmap.createBitmap(measuredWidth, measuredHeight, Bitmap.Config.ARGB_8888)
r.eraseColor(Color.TRANSPARENT)
val canvas = Canvas(r)
draw(canvas)
return r }

Conversion of Layout or view to bitmap :
private Bitmap createBitmapFromLayout(View tv) {
int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
tv.measure(spec, spec);
tv.layout(0, 0, tv.getMeasuredWidth(), tv.getMeasuredHeight());
Bitmap b = Bitmap.createBitmap(tv.getMeasuredWidth(), tv.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
c.translate((-tv.getScrollX()), (-tv.getScrollY()));
tv.draw(c);
return b;
}
Without xml:
private Bitmap createBitmapFromView() {
TextView tv = new TextView(this);
tv.setText("Hello Android !!");
tv.setTextColor(Color.WHITE);
tv.setBackgroundColor(Color.GRAY);
int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
tv.measure(spec, spec);
tv.layout(0, 0, tv.getMeasuredWidth(), tv.getMeasuredHeight());
Bitmap b = Bitmap.createBitmap(tv.getMeasuredWidth(), tv.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
c.translate((-tv.getScrollX()), (-tv.getScrollY()));
tv.draw(c);
return b;
}

All answers using drawing on the canvas won't work with a GLSurfaceView.
To capture the content of a GLSurfaceView into a bitmap you should consider to implement a custom method with gl.glReadPixels inside Renderer::onDrawFrame().
A solution snippet has been posted here.

since API level 24 there is a better way with PixelCopy
example of use:
/**
* use [PixelCopy] to take a snap shoot of the given view
*/
fun copyViewPixelsToBitmap(window: Window?, view: View): Bitmap {
val snap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
val listener = PixelCopy.OnPixelCopyFinishedListener {
if (it != PixelCopy.SUCCESS) {
Log.d("copyViewPixelsToBitmap failed with error: $it")
}
}
val xy = IntArray(2)
view.getLocationInWindow(xy)
val rect = Rect(xy[0], xy[1], xy[0] + view.width, xy[1] + view.height)
window?.let {
PixelCopy.request(it, rect, snap, listener,
Handler(Looper.getMainLooper()))
}
return snap
}

To get a bitmap exactly as it is shown on the screen, you can use the view after it has been displayed with a Runnable:
void viewToBitmap(View view) {
view.post(new Runnable() {
#Override
public void run() {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
// Do stuff
}
});
}

Just use the below code to straight:This will convert any view(FrameLayout/LinearLayout/RelativeLayout/etc) to the bitmap.
private Bitmap getBitmapFromView(View view) {
view.setDrawingCacheEnabled(true);
return view.getDrawingCache();
}

Related

how to get a complete screenshot if you have a very long activity with scrollbar

If your activity has too much content and display a very long ui, like containing a ListView or WebView,
How can we get a screenshot containing the whole content within a long image?
I think the answer in this link can help you:
How to convert all content in a scrollview to a bitmap?
I mixed two answers in the link above to make an optimized piece of code for you:
private void takeScreenShot()
{
View u = ((Activity) mContext).findViewById(R.id.scroll);
HorizontalScrollView z = (HorizontalScrollView) ((Activity) mContext).findViewById(R.id.scroll);
int totalHeight = z.getChildAt(0).getHeight();
int totalWidth = z.getChildAt(0).getWidth();
Bitmap b = getBitmapFromView(u,totalHeight,totalWidth);
//Save bitmap
String extr = Environment.getExternalStorageDirectory()+"/Folder/";
String fileName = "report.jpg";
File myPath = new File(extr, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage(mContext.getContentResolver(), b, "Screen", "screen");
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Bitmap getBitmapFromView(View view, int totalHeight, int totalWidth) {
int height = Math.min(MAX_HEIGHT, totalHeight);
float percent = height / (float)totalHeight;
Bitmap canvasBitmap = Bitmap.createBitmap((int)(totalWidth*percent),(int)(totalHeight*percent), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(canvasBitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
canvas.save();
canvas.scale(percent, percent);
view.draw(canvas);
canvas.restore();
return canvasBitmap;
}
Try using this,
Pass your view to this function,
public Bitmap getBitmapFromView(View view) {
// Define a bitmap with the same size as the view
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.RGB_565);
// Bind a canvas to it
Canvas canvas = new Canvas(returnedBitmap);
// Get the view's background
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
// has background drawable, then draw it on the canvas
bgDrawable.draw(canvas);
else
// does not have background drawable, then draw white background on
// the canvas
canvas.drawColor(Color.WHITE);
// draw the view on the canvas
view.draw(canvas);
// return the bitmap
return returnedBitmap;
}
This function will return a bitmap, you can utilize it the way you want.
You can easily convert layout into "bitmap image"
protected Bitmap ConvertToBitmap(LinearLayout layout) {
layout.setDrawingCacheEnabled(true);
layout.buildDrawingCache();
Bitmap bitmap = layout.getDrawingCache();
return bitmap;
}

Android view to bitmap with tranparency

I need to convert TextView to bitmap. TextView has transparency using the setAlpha() method. I am using following code
Bitmap b = getBitmapFromView(textView , 150);
try {
b.compress(Bitmap.CompressFormat.PNG, 95, new FileOutputStream(watermarkImagePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
public Bitmap getBitmapFromView(View view, int alpha) {
view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint alphaPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
alphaPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));
alphaPaint.setColor(Color.TRANSPARENT);
Toast.makeText(VideoCaptureActivity.this, "alpha" + alpha, Toast.LENGTH_LONG).show();
alphaPaint.setAlpha(alpha);
canvas.drawBitmap(bitmap,0,0,alphaPaint);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.draw(canvas);
return bitmap;
}
but the issue is that the result image has no transparency :(
After trying different techniques what worked for me was to make bitmap from view with full opacity and then set tranparency of bitmap. Hope it will help others having same issue
Bitmap b = addTranparencyToBitmap(getBitmapFromView(view), (int)( view.getAlpha() * 255));
try {
b.compress(Bitmap.CompressFormat.PNG, 95, new FileOutputStream(watermarkImagePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
public Bitmap getBitmapFromView(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
public Bitmap addTranparencyToBitmap(Bitmap originalBitmap, int alpha) {
Bitmap newBitmap = Bitmap.createBitmap(originalBitmap.getWidth(), originalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newBitmap);
Paint alphaPaint = new Paint();
alphaPaint.setAlpha(alpha);
canvas.drawBitmap(originalBitmap, 0, 0, alphaPaint);
return newBitmap;
}

how to convert a Picture object into a Bitmap object, Android

how can I convert a Picture into a Bitmap, what I tried in the code is not working. Any Ideas on how to do this? I wanted to get the image in the Picture object and put that image into the ImageView named imageOne.
showBitmap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Picture picture = wv.capturePicture();
Bitmap bm = Bitmap.createBitmap(picture.getWidth(),
picture.getHeight(),
Bitmap.Config.RGB_565);
Canvas c = new Canvas(bm);
picture.draw(c);
imageOne.setImageBitmap(bm);
}
});
Add this:
//Convert Picture to Bitmap
private static Bitmap pictureDrawable2Bitmap(Picture picture) {
PictureDrawable pd = new PictureDrawable(picture);
Bitmap bitmap = Bitmap.createBitmap(pd.getIntrinsicWidth(), pd.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawPicture(pd.getPicture());
return bitmap;
}
Reference: Android - How to convert picture from webview.capturePicture() to byte[] and back to bitmap
Then modify your code as follows:
showBitmap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Picture picture = wv.capturePicture();
Bitmap bm = pictureDrawable2Bitmap(picture);
imageOne.setImageBitmap(bm);
}
});
private static Bitmap pictureDrawable2Bitmap(Picture picture) {
final int width = picture.getwidth();
final int height = picture.getHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawPicture(picture, new Rect(0, 0, width, height));
return bitmap;
}

Merge two bitmaps in android

I want to merge two bitmaps, here is my code
// Camera arg conversion to Bitmap
Bitmap cameraBitmap = BitmapFactory.decodeByteArray(arg0, 0,
arg0.length);
Bitmap back = Bitmap.createBitmap(cameraBitmap.getWidth(),
cameraBitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas cam = new Canvas(back);
cam.drawBitmap(cameraBitmap, matrix, null);
// FrameLayout to Bitmap
FrameLayout mainLayout = (FrameLayout) findViewById(R.id.frame);
Bitmap foreground = Bitmap.createBitmap(mainLayout.getWidth(),
mainLayout.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(foreground);
mainLayout.draw(c);
Bitmap cs = null;
cs = Bitmap.createBitmap(foreground.getWidth(), cameraBitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(cs);
comboImage.drawBitmap(cameraBitmap, 0f, 0f, null);
comboImage.drawBitmap(foreground, 0f, cameraBitmap.getHeight(), null);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
if (fos != null) {
cs.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
The camera image should become background, and foreground as top image. I've tried from
Combining 2 Images in Android using Canvas but it didn't help me. Any idea.? Thanks
From your example, you forgot to add the next lines:
comboImage.drawBitmap(c, 0f, 0f, null);
comboImage.drawBitmap(s, 0f, c.getHeight(), null);
In your example above you don't draw your image in the canvas, and that is the problem.
You can think that your canvas i your sketchbook. For now you didn't paint anything, and you ask yourself, way I can't see any colors.
So, for my advice, first create the two bitmaps, then, do the next thing:
c.drawBitmap(cameraBitmap, top point, left point, null);
c.drawBitmap(foreground, top point, left point, null);
You can also do this by first create the drawable objects from your bitmaps, like in the next code:
Drawable cameraBitmap = BitmapDrawable(cameraBitmap);
Drawable foreground= BitmapDrawable(foreground);
Then when you have the drawable objects, you can set thier bounds, and that way you set where do you want to show that image.
cameraBitmap.setBounds(left, top, right, bottom);
foreground.setBounds(left, top, right, bottom);
and finally draw that on the canvas:
cameraBitmap.draw(canvas);
foreground.draw(canvas);
EDIT:
This is an example, use this to understand your implementation:
Bitmap bitmap = null;
try {
bitmap = Bitmap.createBitmap(500, 500, Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
Resources res = getResources();
Bitmap bitmap1 = BitmapFactory.decodeResource(res, R.drawable.test1); //blue
Bitmap bitmap2 = BitmapFactory.decodeResource(res, R.drawable.test2); //green
Drawable drawable1 = new BitmapDrawable(bitmap1);
Drawable drawable2 = new BitmapDrawable(bitmap2);
drawable1.setBounds(100, 100, 400, 400);
drawable2.setBounds(150, 150, 350, 350);
drawable1.draw(c);
drawable2.draw(c);
} catch (Exception e) {
}
return bitmap;
This is what I get from the code above:
Merging Two Bitmap vertically when one is large and second is small
follow this method
public Bitmap finalcombieimage(Bitmap c, Bitmap s) {
Bitmap cs = null;
DisplayMetrics metrics = getBaseContext().getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(cs);
Rect dest1 = new Rect(0, 0, width, height); // left,top,right,bottom
comboImage.drawBitmap(c, null, dest1, null);
Rect dest2 = new Rect(0, height-400 / 2, width, height);
comboImage.drawBitmap(s, null, dest2, null);
return cs;
}
Please note that the BitmapDrawable(Bitmap) has been deprecated. Kinldy check this for the alternative.
BitmapDrawable(Bitmap bitmap)
This constructor was deprecated in API level 4. Use BitmapDrawable(Resources, Bitmap) to ensure that the drawable has correctly set its target density.
Resize watermark image same size as original image
Uri bmpUri1 = getLocalBitmapUri(ivImage);
Uri bmpUri2 = getLocalBitmapUri(watermark_imageview);
try {
bm1 = BitmapFactory.decodeStream(
getContentResolver().openInputStream(bmpUri1));
bm2 = BitmapFactory.decodeStream(
getContentResolver().openInputStream(bmpUri2));
Bitmap bmOverlay = Bitmap.createBitmap(bm1.getWidth(), bm1.getHeight(), bm1.getConfig());
bm2 = Bitmap.createScaledBitmap(bm2, bm1.getWidth(), bm1.getHeight(),
true);
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bm1, 0,0, null);
canvas.drawBitmap(bm2, 0,0, null);
watermarkimage.setVisibility(View.GONE);
im =new ImageView(ImageClick.this);
im.setImageBitmap(bmOverlay);
bmpUri = getLocalBitmapUri(im);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
private Uri getLocalBitmapUri(ImageView imageView) {
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable){
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}

Make image as canvas background and save it with user's drawing

I'm using the code below. My app was able to draw on the canvas and save it.
But what I want to do is make an image as the background of the canvas so when I save it, it will look like an image with the user's drawing on top of it.
Thank you so much for any help! :)
#Override
public void run() {
Canvas canvas = null;
while (_run){
if(isDrawing == true){
try{
canvas = mSurfaceHolder.lockCanvas(null);
if(mBitmap == null){
mBitmap = Bitmap.createBitmap (1, 1, Bitmap.Config.ARGB_8888);
}
final Canvas c = new Canvas (mBitmap);
c.drawColor(0, PorterDuff.Mode.CLEAR);
canvas.drawColor(0, PorterDuff.Mode.CLEAR);
canvas.drawColor(0xffffffff);
commandManager.executeAll(c,previewDoneHandler);
previewPath.draw(c);
canvas.drawBitmap (mBitmap, 0, 0,null);
} finally {
mSurfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
Try this stuff,
This will return a Bitmap that will be a Merged one of two Bitmap Images, also it will save in the SDCard.
public Bitmap combineImages(Bitmap c, Bitmap s) {
Bitmap cs = null;
int width, height = 0;
if (c.getWidth() > s.getWidth()) {
width = c.getWidth();
height = c.getHeight();
} else {
width = s.getWidth() + s.getWidth();
height = c.getHeight();
}
cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(cs);
comboImage.drawBitmap(c, 0, 0, null);
comboImage.drawBitmap(s, 100, 300, null);
/******
*
* Write file to SDCard
*
* ****/
String tmpImg = String.valueOf(System.currentTimeMillis()) + ".png";
OutputStream os = null;
try {
os = new FileOutputStream(Environment.getExternalStorageDirectory()
+ "/"+tmpImg);
cs.compress(CompressFormat.PNG, 100, os);
} catch (IOException e) {
Log.e("combineImages", "problem combining images", e);
}
return cs;
}
For any view that you are creating, you can create a bitmap of what it is currently displaying.
use:
view.setDrawingCacheEnabled(true);
Bitmap bitmap=view.getDrawingCache();
Does this help you in achieving what you want ?
*be sure to recycle these bitmaps when you are done.
bitmap.recycle();

Categories

Resources