i want to create a bitmap of whats being currently displayed of my app, one thing i went into is cant read FB buffer requires root, would like to know if it is possible to create a image file for the screen, please i want the help to code this, no 3rd party intents , thanks, answers would be much appreciated
From your Activity (pseudo-code):
Bitmap bm = Bitmap.create...
Canvas canvas = new Canvas(bm);
getWindow.getDecorView().draw(canvas);
You can use FFMPEG to capture the Screen
Try this.....
{
LinearLayout view = (LinearLayout) findViewById(R.id.imageLayout);
View v1 = view.getRootView();
v1.setDrawingCacheEnabled(true);
String dir="myimages";
Bitmap bm = v1.getDrawingCache();
saveBitmap(bm, dir, "capturedimage");
}
static String saveBitmap(Bitmap bitmap, String dir, String baseName) {
try {
File sdcard = Environment.getExternalStorageDirectory();
File pictureDir = new File(sdcard, dir);
pictureDir.mkdirs();
File f = null;
for (int i = 1; i < 200; ++i) {
String name = baseName + i + ".png";
f = new File(pictureDir, name);
if (!f.exists()) {
break;
}
}
System.out.println("Image size : "+bitmap.getHeight());
if (!f.exists()) {
String name = f.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(name);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
System.out.println("After File Size : "+f.length());
fos.flush();
fos.close();
return name;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception in saveBitmap: "+e.getMessage());
} finally {
}
return null;
}
Related
My app has an Export feature which exports a copy of a ScrollView.
The Scrollview (including a background image) is set programatically, but when I export a copy of it, the background appears black.
I call two functions, takeScreenshot() and then saveBitmap()
How can I include the background image?
private android.graphics.Bitmap takeScreenshot(View scroll) {
ScrollView iv = findViewById(R.id.scroll);
Bitmap bitmap = Bitmap.createBitmap(
iv.getChildAt(0).getWidth(),
iv.getChildAt(0).getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
iv.getChildAt(0).draw(c);
return bitmap;
}
public void saveBitmap(Bitmap bitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root+"/NPCdata");
boolean test = newDir.mkdirs();
if (test){
String photoname = myNPC.getNpcMap().get("Name");
assert photoname != null;
photoname.replaceAll("\\s+", "");
String fotoname = photoname+".jpg";
File file = new File(newDir, fotoname);
while (file.exists()){
fotoname = photoname+"a"+".jpg";
file = new File(newDir, fotoname);
}
try {
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
fos.flush();
fos.close();
Toast.makeText(getApplicationContext(),
"Saved in folder: 'NPCdata'", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
I solved this by adding the Background to the LinearLayout inside the ScrollView
scroll = new ScrollView(this);
scroll.setBackgroundResource(R.drawable.back);
scroll.setFillViewport(true);
contentView = new LinearLayout(this);
contentView.setBackgroundResource(R.drawable.back);// <-- this makes it work
I have images in my drawables folder. Activity opens them, I choose the needed images and click on button. They must be saved on my SD Card through ImageSavingTask class instance execution which extends AsyncTask.
Here is my onClick code:
#Override
public void onClick(View v) {
for (int i = 0; i < 26; i++)
if (checkBoxes[i].isChecked()) {
imageIndex = new ImageIndex(); //ImageIndex-a class with single index field which reserves the checked checkbox indexes.
imageIndex.index = i;
Bitmap bitmap = ((BitmapDrawable) (images[i].getDrawable())).getBitmap();
SaveImageTask saveImageTask = new SaveImageTask();
saveImageTask.execute(bitmap); //The class SaveImageTask extends AsyncTask<Bitmap, Void, Void>
}
}
Then the selected images are handled in doInBackground method.
#Override
protected Void doInBackground(Bitmap... params) {
FileOutputStream outStream = null;
try {
Bitmap bitmap = params[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageBytes = stream.toByteArray();
File sdCard = Environment.getExternalStorageDirectory();
Drawable drawable = new BitmapDrawable(getResources(), bitmap);
File dir = new File(sdCard.getAbsolutePath());
dir.mkdirs();
String fileName = "Saved image " + imageIndex.index; //The reserved index of checkbox creates a name for the new file.
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
outStream.write(imageBytes);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
The <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> line is added in my manifest.
After I connect the USB to my phone, no error happens, but no images are saved to my SD Card. And I can't find images on my phone using windows search. Debugging doesn't give any answer. What kind of problem this could be?
It seems you have not asked runtime permissions for writing file on SD Card. From Android M and above you need to ask write permission at runtime to save any file on external sd card.
Check this link on how to request runtime permissions- https://developer.android.com/training/permissions/requesting.html
Also you can use google library - https://github.com/googlesamples/easypermissions
to request permissions.
I add the selected indexes into 2 ArrayLists of indexes and bitmaps. In the doInBackground method I created a loop.
For appearing the images on the card immediately I used the MediaScannerConnection.scanFile method.
for (int i = 0; i < 26; i++)
if (checkBoxes[i].isChecked()) {
index.add(i);
bitmap.add(bitmaps[i]);
}
if (bitmap.size() > 0)
new SaveImageTask().execute();
The doInBackground method:
protected Void doInBackground(Void... params) {
for (int i = 0; i < bitmap.size(); i++) {
try {
fname = "Saved image " + (index.get(i)) + ".jpg";
file = new File(myDir, fname);
if (file.exists()) file.delete();
FileOutputStream out = new FileOutputStream(file);
bitmap.get(i).compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
MediaScannerConnection.
scanFile(getApplicationContext(), new String[]{file.getPath()}, new String[]{"image/jpeg"}, null);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
I left the ImageSavingTask without fields and parameters.
I think problem where you try to write bytes.
Use Following Solution..
#Override
protected Void doInBackground(Bitmap... params) {
Bitmap bitmap = params[0];
saveToInternalStorage(bitmap, "MyImage"); // pass bitmap and ImageName
return null;
}
//Method to save Image in InternalStorage
private void saveToInternalStorage(Bitmap bitmapImage, String imageName) {
File mypath = new File(Environment.getExternalStorageDirectory(), imageName + ".jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
NOTE : Make sure you have added storage read/write permission and don't forget to ask permission on Marshmallow and higher version.
I am trying to get screenshot of the view as follows. I am getting Bitmap and I need to convert it to to Image to add into PDF generator.
using (var screenshot = Bitmap.CreateBitmap(200, 100,Bitmap.Config.Argb8888))
{
var canvas = new Canvas(screenshot);
rootView.Draw(canvas);
using (var screenshotOutputStream = new FileStream(screenshotPath,System.IO.FileMode.Create))
{
screenshot.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 90, screenshotOutputStream);
screenshotOutputStream.Flush();
screenshotOutputStream.Close();
}
}
My question is how to convert Android.Graphics.Bitmap -->screenshot to Image ?
I want to replace the url with Image itself which comes from BitMap.
String imageUrl = "myURL";
Image image = Image.GetInstance (new Uri (imageUrl));
document.Add(image);
You can use this method:
public Bitmap getScreenshotBmp() {
FileOutputStream fileOutputStream = null;
File path = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String uniqueID = UUID.randomUUID().toString();
File file = new File(path, uniqueID + ".jpg");
try {
fileOutputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
screenshot.compress(Bitmap.CompressFormat.JPEG, 30, fileOutputStream);
try {
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return screenshot;
}
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.
I have saved a bitmap to external storage via FileOutputStream and am trying to retrieve that file in another class so that it can be put into a imageView. Here is where I save the bitmap:
public void SaveImage(Bitmap default_b) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 100000;
n = generator.nextInt(n);
String fname = "Image-" + n +".png";
File file = new File (myDir, fname);
Log.i("AppInfoAdapter", "" + file);
if (file.exists()) file.delete();
try {
// File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
// + "/" + fname + ".png");
// FileOutputStream out = mContext.getApplicationContext().openFileOutput("bitmapA", Context.MODE_WORLD_WRITEABLE);
FileOutputStream out = new FileOutputStream(file);
default_b.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
and I am trying to recieve it here:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(Context);
Log.d("GridViewAdapter", "new imageView added");
}
try {
FileInputStream in = Context.openFileInput("bitmapA");
BufferedInputStream buf = new BufferedInputStream(in);
byte[] bitMapA = new byte[buf.available()];
buf.read(bitMapA);
Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
view.setImageBitmap(bM);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
e.printStackTrace();
}
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
I have done plenty of searching on this and have come across multiple ways of doing the same thing but for at the moment, this way of doing it doesn't work.
I have seen it where you use openFileOutput and openFileInput and then I have also seen where people just create new FileInput and Output streams.
Which one is better to use for the bitmap?
and then depending on which one is better to use (since I have both set up for when I save the bitmap), how can I get that bitmap from external storage?
Thanks!