how to convert PictureDrawable into Bitmap - android

how can I convert a PictureDrawable object into a Bitmap object? I tried the following code shown below and it gives null pointer.
//Convert PictureDrawable to Bitmap
private Bitmap pictureDrawable2Bitmap(PictureDrawable pictureDrawable){
Bitmap bitmap = Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth(),pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888);
Toast.makeText(HTMLActivity.this, "bitmap " + bitmap.toString(), Toast.LENGTH_LONG).show();
Canvas canvas = new Canvas(bitmap);
canvas.drawPicture(pictureDrawable.getPicture());
return bitmap;
}
Here is sample to show what I am doing in my code;
private Picture picture;
private String url;
private WebView webview;
private Bitmap HTMLBitmap;
private PictureDrawable HTMLPicDraw;
// goal is to convert WebView --> Picture --> PictureDrawable --> Bitmap
picture = webview.capturePicture();
HTMLPicDraw = new PictureDrawable(picture);
// HTMLPicDraw a PictureDrawable object is good, no null pointer exception here
// what is left is to go from PictureDrawable to Bitmap

use belove code it's working for me.....
// get bitmap from view
public static Bitmap getBitmapFromView(View view) {
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable =view.getBackground();
if (bgDrawable!=null)
bgDrawable.draw(canvas);
/* else
canvas.drawColor(Color.WHITE);*/
view.draw(canvas);
return returnedBitmap;
}

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;
}

How to use Canvas for merging two images in Android?

I want to create a combined image with two different images by overlapping.
For this My code is
ImageView image = (ImageView) findViewById(R.id.imageView1);
Drawable drawableFore = getResources().getDrawable(R.drawable.foreg);
Drawable drawableBack = getResources().getDrawable(R.drawable.backg);
Bitmap bitmapFore = ((BitmapDrawable) drawableFore).getBitmap();
Bitmap bitmapBack = ((BitmapDrawable) drawableBack).getBitmap();
Bitmap scaledBitmapFore = Bitmap.createScaledBitmap(bitmapFore, 35, 35, true);
Bitmap scaledBitmapBack = Bitmap.createScaledBitmap(bitmapBack, 45, 45, true);
Bitmap combineImages = overlay(scaledBitmapBack, scaledBitmapFore);
image.setImageBitmap(combineImages);
overlay() method is
public static Bitmap overlay(Bitmap bmp1, Bitmap bmp2)
{
try
{
Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bmp1, new Matrix(), null);
canvas.drawBitmap(bmp2, 0, 0, null);
return bmOverlay;
} catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
return null;
}
}
case 1 :overlay method returns null in this case.
case 2: But when I switch images like I use background image for setting in foreground and foreground image for setting in background then code works fine.
but I want the first case should work properly but it is not.
I am not getting why this is happening.
Please Help
I think it happens, because the 2nd bitmap is bigger in size. So try this:
public static Bitmap overlay(Bitmap bmp1, Bitmap bmp2)
{
try
{
int maxWidth = (bmp1.getWidth() > bmp2.getWidth() ? bmp1.getWidth() : bmp2.getWidth());
int maxHeight = (bmp1.getHeight() > bmp2.getHeight() ? bmp1.getHeight() : bmp2.getHeight());
Bitmap bmOverlay = Bitmap.createBitmap(maxWidth, maxHeight, bmp1.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bmp1, 0, 0, null);
canvas.drawBitmap(bmp2, 0, 0, null);
return bmOverlay;
} catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
return null;
}
}

Convert view to bitmap on 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();
}

Categories

Resources