In my android app i have surface view on which i have canvas and user can draw on canvas.Now i want to capture canvas image and store it to sd card.
Below is my code -
Bitmap bitmap = Bitmap.createBitmap(maxX, maxY, Bitmap.Config.RGB_565);
canvas.setBitmap(bitmap);
String mFile = path+"/drawing.png";
Bitmap bitmap = drawBitmap();
File file = new File(mFile);
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
code is run but when i open sd card on image path file with name is created but when open image it is black.
How to capture image from canvas in android.
Just pass the your surface view object and file path where you want to store your snapshot. It is working perfectly.
public static void takeScreenshot(View view, String filePath) {
Bitmap bitmap = getBitmapScreenshot(view);
File imageFile = new File(filePath);
imageFile.getParentFile().mkdirs();
try {
OutputStream fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Bitmap getBitmapScreenshot(View view) {
view.measure(MeasureSpec.makeMeasureSpec(view.getWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(view.getHeight(), MeasureSpec.EXACTLY));
view.layout((int)view.getX(), (int)view.getY(), (int)view.getX() + view.getMeasuredWidth(), (int)view.getY() + view.getMeasuredHeight());
view.setDrawingCacheEnabled(true);
view.buildDrawingCache(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return bitmap;
}
Related
I am taking screenshot programmatically using the following code:
public static Bitmap takeScreenshot(View view)
{
try
{
// create bitmap screen capture
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return bitmap;
}
catch (Throwable e)
{
CustomLogHandler.printError(e);
}
return null;
}
private static void copyFile(Bitmap bitmap)
{
File dstFile = getShareResultFile();
//Delete old file if exist.
if(dstFile.exists()) {
dstFile.delete();
}
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(dstFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 0, fos);
fos.flush();
}
catch (Exception e) {
CustomLogHandler.printError(e);
}
finally {
if (fos != null) {
try {
fos.close();
} catch (IOException ioe) {
CustomLogHandler.printError(ioe);
}
}
}
}
There are several problem like:
Back arrow, title and share menu background color is not correct. It looks messy.
Background color of toolbar is totally changed.
Image quality is too poor and list items rounded drawable has not smooth corners.
Background of layout is not taken that I set as background of my parent layout.
I am taking the screenshot from the root view.
bitmap.compress(Bitmap.CompressFormat.JPEG, 0, fos);
First, you are saving this as a JPEG. JPEG is designed for photos, and your screenshot is not a photo.
Second, you are saving this with a quality factor of 0. JPEG uses a lossy compression algorithm, and a quality factor of 0 says "please feel free to make this image be really poor, but compress it as far as you can".
I suggest switching to:
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
PNG is a better image format for a screenshot with the contents shown in your question. I don't think PNG uses the quality factor value; I put in 100 just to indicate that you want the best possible quality.
public static Bitmap takeScreenshot(View view)
{
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
This code can save view as bitmap.
But after you update your question with save code I see that you set 0 for quality, and what you expect?
#param quality Hint to the compressor, 0-100. 0 meaning compress for
* small size, 100 meaning compress for max quality. Some
* formats, like PNG which is lossless, will ignore the
* quality setting
just use your Ctrl button + click on method name to read doc about params
the answer is set second parameter 100 instead of 0!
Try using this:
public static Bitmap loadBitmapFromView(Context context, View v) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
v.measure(MeasureSpec.makeMeasureSpec(dm.widthPixels, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(dm.heightPixels, 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;
}
and
public void takeScreen() {
Bitmap bitmap = ImageUtils.loadBitmapFromView(this, view); //get Bitmap from the view
String mPath = Environment.getExternalStorageDirectory() + File.separator + "screen_" + System.currentTimeMillis() + ".jpeg";
File imageFile = new File(mPath);
OutputStream fout = null;
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
fout.close();
}
}
Images are saved in the external storage folder.
try this
private void captureScreen() {
View v = this.getWindow().getDecorView().findViewById(android.R.id.content);
v.setDrawingCacheEnabled(true);
Bitmap bitmap = v.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File file = new File(extr, getString(R.string.free_tiket) + ".jpg");
FileOutputStream f = null;
try {
f = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, f);
f.flush();
f.close();
MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "Screen", "screen");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
In my app i want to capturea a part of my android application UI and save it programmatically .
For example i want do this actions :
In Activity/Fragment user clicks one Button .
capture from a part of Layout for example a LinearLayout that have id="captureMe" .
Save captured image somewhere .
how i can implement it ?
You can simply use this function just pass your view object
public Bitmap viewToBitmap(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
Then Save this file
public void saveImage(Bitmap inImage) {
String root = Environment.getExternalStorageDirectory().toString();
File mydir = new File(root + "/demo/");
mydir.mkdirs();
String fname = "Image.jpeg";
File file = new File (mydir, fname);
String path2=file.getPath();
Uri uri=Uri.fromFile(file);
try {
FileOutputStream out = new FileOutputStream(file);
inImage.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}catch (Exception e)
{
e.printStackTrace();
}
}
Try this, hope it works
LinearLayout captureMe = (LinearLayout)findViewById(R.id.captureMe);
captureMe.setDrawingCacheEnabled(true);
captureMe.buildDrawingCache();
bitmap = captureMe.getDrawingCache();
First Use this function to get bitmap of view that you want to capture:
public static Bitmap getViewBitmap(View v, int width, int height) {
Bitmap viewBitmap = Bitmap.createBitmap(width , height,
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(viewBitmap);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
return viewBitmap;
}
Then use this code to save this bitmap to storage:
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOutputStream = null;
File file = new File(path + "/Captures/", "screen.jpg");
try {
fOutputStream = new FileOutputStream(file);
capturedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOutputStream);
fOutputStream.flush();
fOutputStream.close();
MediaStore.Images.Media.insertImage(getContentResolver(),
file.getAbsolutePath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "Save Failed", Toast.LENGTH_SHORT).show();
return;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Save Failed", Toast.LENGTH_SHORT).show();
return;
}
I have long scrollview almost 50+ fields.
I'm converting that scrollview to pdf view. pdf also creating all done.
But pdf file showing data is blur (too blur).
With some merging, I provided some reference image (I mean output image).
output image
My code:
private void takeScreenShot() {
try {
//here getScroll is my scrollview id
View u = ((Activity) mContext).findViewById(R.id.getScroll);
ScrollView z = (ScrollView) ((Activity) mContext).findViewById(R.id.getScroll);
int totalHeight = z.getChildAt(0).getHeight();
int totalWidth = z.getChildAt(0).getWidth();
Bitmap bitmap = getBitmapFromView(u,totalHeight,totalWidth);
Image image;
//Save bitmap
String path = Environment.getExternalStorageDirectory()+"/Folder/";
String fileName = "report1.pdf";
File dir = new File(path);
if (!dir.exists())
dir.mkdirs();
Log.v("PDFCreator", "PDF Path: " + path);
File myPath = new File(path, fileName);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 10, stream);
image = Image.getInstance(stream.toByteArray());
image.setAbsolutePosition(0, 0);
Document document = new Document(image);
PdfWriter.getInstance(document, new FileOutputStream(myPath));
document.open();
document.add(image);
document.close();
} catch (Exception i1) {
i1.printStackTrace();
}
}
Any help?
Try this code:
View u = ((Activity) mContext).findViewById(R.id.getScroll);
u.setDrawingCacheEnabled(true);
u.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(u.getDrawingCache());
bitmap.setHasAlpha(true); //important for PNG
---------------DO SAVE WORK-----------------
v1.setDrawingCacheEnabled(false);
And at
bitmap.compress(Bitmap.CompressFormat.JPEG, 10, stream);
change 10 to 90 or 100. it is Image Quality.
Or just change in your code to higher quality.
Try another solution:
ScrollView v= (ScrollView)findViewById(R.id.getScroll);
int height = v.getChildAt(0).getHeight()
int width = v.getWidth()
Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Take a screen shot using this code and
ScrollView iv = (ScrollView) findViewById(R.id.scrollView);
Bitmap bitmap = Bitmap.createBitmap(
iv.getChildAt(0).getWidth(),
iv.getChildAt(0).getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
c.drawColor(Color.WHITE);
iv.getChildAt(0).draw(c);
// Do whatever you want with your bitmap
saveBitmap(bitmap);
and save the bitmap as a image
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}}
I might be late but anyway. Use png format instead, increase the quality to 100 and replace
View u = ((Activity) mContext).findViewById(R.id.getScroll);
with
View u = ((Activity) mContext).findViewById(R.id.yourfirstscrollviewchild);
Thatll do the trick.
I want to take screenshot of a layout from another activity. When I take view into Bitmap it shows NullPointerExcenption. Here is my code
View v=LayoutInflater.from(this).inflate(R.layout.score_share, null);
layoutScore.setDrawingCacheEnabled(true);
Bitmap bm= Bitmap.createBitmap(v.getDrawingCache());
layoutScore.setDrawingCacheEnabled(false);
File file= new File(Environment.getExternalStorageDirectory()+"/scs.jpg");
try {
FileOutputStream outputStream= new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG,100, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Below is the method to capture screenshot.
public Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
Store the Bitmap into the SDCard:
public void store(Bitmap bm, String fileName){
final static String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
File dir = new File(dirPath);
if(!dir.exists())
dir.mkdirs();
File file = new File(dirPath, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Now Inflate your layout and capture screen shot
View view=LayoutInflater.from(this).inflate(R.layout.score_share, null);
Bitmap bmp = getScreenShot(view);
bmp is the required screenshot then save it to SDcard like
store(bmp, "Screenshot.jpg");
Don't forget to add Write External Storage permission in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Thanks to this answer Capture Screenshot and store to sdcard
If the problem is getDrawingCache returning null, then just add this lines of code before v.buildDrawingCache(true);
v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
This will prevent that the view has a size of (0,0), and because of that it turns null safe.
I have this code for take screenshot of current view, a fragment that lives into an activity, where the activity has only a background.
private File captureScreen() {
Bitmap screenshot = null;
try {
if (view != null) {
screenshot = Bitmap.createBitmap(view.getMeasuredWidth(),
view.getMeasuredHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(screenshot);
view.draw(canvas);
// save pics
File cache_dir = Environment.getExternalStorageDirectory();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
screenshot.compress(Bitmap.CompressFormat.PNG, 90, bytes);
File f = new File(cache_dir + File.separator + "screen.png");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
return f;
}
} catch (Exception e) {
// TODO
}
return null;
}
but bitmap saved is not exactly what i'm expecting.
Screenshot take only fragment elements, but not activity background. How can i include it into screenshot?
From :How to programmatically take a screenshot in Android?
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + ACCUWX.IMAGE_APPEND;
// create bitmap screen capture
Bitmap bitmap;
View v1 = mCurrentUrlMask.getRootView();
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.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try this. it work for me. and for you too
Call this method, passing in the outer most ViewGroup that you want a screen shot of:
public Bitmap screenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
I've used it for a while in a few different apps and haven't had any issues. Hope it vll helps