Take snapshoot from MapBox mapView (Android) - android

I want to get a picture from a MapBox MapView, but only returns a transparent image with MapBox Logo.
Transparent snapshot
This is the code, thanks!:
public File 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);
File file = new File(Utils.getAppFolder() + currentTrack.getDate().toString().replace(" ", "_").replace(":","_") + ".png");
try{
file.createNewFile();
}catch(IOException e){
Utils.logError("IOException: Exception in create new File: " + e.toString() );
}
FileOutputStream fileos = null;
try{
fileos = new FileOutputStream(file);
}catch(FileNotFoundException e){
Log.e("FileNotFoundException",e.toString());
}
returnedBitmap.compress(Bitmap.CompressFormat.PNG, 80, fileos);
return file;
}

First add permission to save file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is the code:
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
}

Solved!,
Here is the explanation and the code to fix this issue
https://github.com/mapbox/mapbox-gl-native/issues/3677

Perform snapshot of current MapView state with notifying listener about it. This method is asynchronous so it does not block calling thread. OnSnapshotReady.onSnapshotReady is called from non UI thread.
mapView.snapshot{bitmap->}

Related

Capture a part of application and save it

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

How to convert xml layout to pdf in android

I tried a lot searching over the internet but I didn't find any solution regarding this. My problem is I have a layout called main.xml whose parent layout is a LinearLayout and it is scrollable. I want to generate a pdf of that layout. The layout consist of reports so I want to export those reports in pdf format. How can I do it Please help.
You can use this library to make it easy to do within a few lines of code -
PdfGenerator.getBuilder()
.setContext(context)
.fromLayoutXMLSource()
.fromLayoutXML(R.layout.layout_your_scroll_view)
.setDefaultPageSize(PdfGenerator.PageSize.A4)
.setFileName("Test-PDF")
.build();
You can also set inflated scroll view(s) instance (both single or multiple views) in it. Additionally you can also pass a callback (PdfGeneratorListener()) in .build() to notify about if the pdf generation is done or failed for an exception
At last I got the solution for my problem. Now I can easily convert any view to PDF using itextpdf.jar file. I will post my code here. This method will save the view in bitmap format.
public void saveViewImage(View view){
File file = saveBitMap(this, layout); //which view you want to pass that view as parameter
if (file != null) {
Log.i("TAG", "Drawing saved to the gallery!");
} else {
Log.i("TAG", "Oops! Image could not be saved.");
}
}
private File saveBitMap(Context context, View drawView){
File pictureFileDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"Handcare");
if (!pictureFileDir.exists()) {
boolean isDirectoryCreated = pictureFileDir.mkdirs();
if(!isDirectoryCreated)
Log.i("ATG", "Can't create directory to save the image");
return null;
}
String filename = pictureFileDir.getPath() +File.separator+ System.currentTimeMillis()+".jpg";
File pictureFile = new File(filename);
Bitmap bitmap =getBitmapFromView(drawView);
try {
createPdf(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
pictureFile.createNewFile();
FileOutputStream oStream = new FileOutputStream(pictureFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, oStream);
oStream.flush();
oStream.close();
} catch (IOException e) {
e.printStackTrace();
Log.i("TAG", "There was an issue saving the image.");
}
scanGallery( context,pictureFile.getAbsolutePath());
return pictureFile;
}
//create bitmap from view and returns it
private 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;
}
Now the below method is used to generate the pdf
private void createPdf(Bitmap bitmap) throws IOException, DocumentException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image signature;
signature = Image.getInstance(stream.toByteArray());
signature.setAbsolutePosition(50f, 100f);
signature.scalePercent(60f);
//Image image = Image.getInstance(byteArray);
File pdfFolder = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS), "pdfdemo");
if (!pdfFolder.exists()) {
pdfFolder.mkdirs();
Log.i("Created", "Pdf Directory created");
}
//Create time stamp
Date date = new Date() ;
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date);
File myFile = new File(pdfFolder + timeStamp + ".pdf");
OutputStream output = new FileOutputStream(myFile);
//Step 1
Document document = new Document();
//Step 2
PdfWriter.getInstance(document, output);
//Step 3
document.open();
//Step 4 Add content
document.add(signature);
//document.add(new Paragraph(text.getText().toString()));
//document.add(new Paragraph(mBodyEditText.getText().toString()));
//Step 5: Close the document
document.close();
}

take screenshot of entire screen programmatically

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

How to take screen-shot of app screen in android?

I am developing an application in which I have to take screen-shot of app screen
right now I used below code it is not working. I am null bitmap image
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/"+ "bs_score_img" +".png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
String screenShot = Environment.getExternalStorageDirectory().toString()+"/bs_score_img.png";
Log.i("TAG:Score: screenShot path=", screenShot);
Bitmap bmp = BitmapFactory.decodeFile(new File(screenShot).getAbsolutePath());
try this :
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
then read img.png as bitmap and convert it jpg as follows
Bitmap screen = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+
File.separator +"img.png");
//my code for saving
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
screen.compress(Bitmap.CompressFormat.JPEG, 15, bytes);
//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()+ File.separator + "test.jpg");
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
// remember close de FileOutput
fo.close();
Google has a library with which you can take screenshot without rooting, I tried that, But i am sure that it will eat out the memory as soon as possible.
Try http://code.google.com/p/android-screenshot-library/
or try this :
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);
I found this code from another post:
// 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();
}
Let's say that you clicked on button
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
}
});
After that you need this two methods
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(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);
}
}
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;
}
just call this method with the view you want a snapshot of.. so if you want the whole screen just pass in you top most ViewGroup. if you want the System controls also just call:
you can try this
private Bitmap getScreen(){
mDecorView = getWindow().getDecorView();
runOnUiThread(new Runnable() {
public void run() {
mDecorView.invalidate();
mDecorView.post(this);
}
});
View v1 = mDecorView.getRootView();
System.out.println("Root View : "+v1);
v1.setDrawingCacheEnabled(true);
return v1.getDrawingCache();
}
here mDecorView is View .
Here how you can capture screen and save it in your storage
give permissions for creating file in external storage
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is code for activity.
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
}
This is how you can capture the screen.

Get screenshot of surfaceView in Android

In my application I have view with some buttons and SurfaceView. I must take screenshot of this view, but in place of SurfaceView is only black field. I try solutions which I found on stackoverflow, but they don't work for me.
This is my code which I usualy take screenshots:
File folder = new File(Environment.getExternalStorageDirectory().getPath() + "/folder");
if (!folder.exists()) {
folder.mkdir();
}
String path = folder.getAbsolutePath() + "snapshot.png";
File file = new File(path);
file.createNewFile();
View view = this.findViewById(android.R.id.content).getRootView();
view.setDrawingCacheEnabled(true);
Bitmap drawingCache = view.getDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(drawingCache);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, fos);
} finally {
bitmap.recycle();
view.setDrawingCacheEnabled(false);
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
}
}
Maybe someone can help.

Categories

Resources