ScreenShot in android is not working - android

This is my code and im trying to capture screenshot of my application.I have background as animation(hearts falling)which looks like a live wallpaper.I want to take screenshot of current page>But its not working.I have used a button to take scrrenshot and imageview to show preview.when button is clicked nothing happens>Iam new to android.Plz help.Thanks in advance!!
View view = findViewById(R.id.Flayout);
view.setDrawingCacheEnabled(true);
Bitmap bitmap = view.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
imgshot = (ImageView) findViewById(R.id.imagescreen);
// set screenshot bitmapdrawable to imageview
imgshot.setBackgroundDrawable(bitmapDrawable);
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState()))
{
// we check if external storage is available, otherwise
// display an error message to the user using Toast Message
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath()
+ "/ScreenShots");
directory.mkdirs();
String filename = "screenshot" + i + ".jpg";
File yourFile = new File(directory, filename);
while (yourFile.exists())
{
i++;
filename = "screenshot" + i + ".jpg";
yourFile = new File(directory, filename);
}
if (!yourFile.exists())
{
if (directory.canWrite())
{
try
{
FileOutputStream out = new FileOutputStream(
yourFile, true);
bitmap.compress(Bitmap.CompressFormat.PNG, 90,
out);
out.flush();
out.close();
Toast.makeText(
ResultActivity.this,
"File exported to /sdcard/ScreenShots/screenshot"
+ i + ".jpg",
Toast.LENGTH_SHORT).show();
i++;
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
} else
{
Toast.makeText(ResultActivity.this,
"Sorry SD Card not available in your Device!",
Toast.LENGTH_SHORT).show();
}
break;
}
}
}

Well, check this out:
How to programmatically take a screenshot in Android?
Here looks like what you want to do (as i understand), so test it out.

you have not get the root view. try this code
File file = new File(Environment.getExternalStorageDirectory()+ File.separator + "myimage.jpg");
// create bitmap
Bitmap bitmap;
View v1 = getWindow().getDecorView().getRootView(); //if this didnt work then try sol -3 at the bottom of this answer
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.close();
if this didnt work
View v1 = mCurrentUrlMask.getRootView();
then try this
View v1 = getWindow().getDecorView().getRootView();
or you can do
sol -3 ) View v1 = findViewById(R.id.linear_layout_id);// add the root view id
Don't forget to add permissions or it wont work:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Related

getWindow() not exist in Service class

I use this code in a service class to take screenshot in the service but getWindow() is not available here. what should i do?
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();
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
}
}
Try this approach:
Pass a reference to the activity when you create the class, and when calling relevant methods and use it. But there can be memory leaks with this approach
void MethodThatUsesActivity(Activity myActivityReference) {
myActivityReference.getWindow().getDecorView().getRootView();
}

How to get a phone display print screen?

How to get Android OS Phone display a screenshot every minute and send it by email?
use following code to get screen shot from your mobile
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();
}
}
add permission in your manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is how you can open the recently generated image:
private void openScreenshot(File imageFile) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
}

Saving a bitmap file in android and reading back to display in Imageview

I have a bitmap file which i need to upload to my php server but as the file is very large I decided to resize it and save it. Later on I try to read it back to display resized image. But this time I am not getting the same image
Below is code for writing image and returning File
public static File savebitmap(Bitmap bmp) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "testimage.jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
return f;
}
Below is code for reading and displaying
File file=ImageUtil.savebitmap(this.bitmap);
this.imgChoosenImage.setImageURI(Uri.parse(file.getAbsolutePath()));
Please tell me what exactly is going wrong here
first check the images are saved in ur path as defined, and Make sure ur giving correct path for retriving image.
I have used this below code for saving imge in gallery
String iconsStoragePath = Environment.getExternalStorageDirectory()+ File.separator;
File sdIconStorageDir = new File(iconsStoragePath);
//create storage directories, if they don't exist
sdIconStorageDir.mkdirs();
try {
String filePath = null;
filePath = Environment.getExternalStorageDirectory() + File.separator + "testimage" + ".jpg";
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
bmp.compress(Bitmap.CompressFormat.JPG, 100, bos);
bos.flush();
bos.close();
} catch (IOException e) {
Log.w("TAG", "Error saving image file: " + e.getMessage());
Toast.makeText(getApplicationContext(), "Failed to Create folder",
Toast.LENGTH_SHORT).show();
}
For bitmap display in imageview :
File imgFile = new File("/sdcard/Images/testimage.jpg");
//Here File file = ur file path
if(imgFile.exists())
{
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
Permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Android .JPG is not saving to the SD card

Im trying to capture user signature and store it under SD Card. App runs without any error.But the image file is not storing to the SD card.it only shows folder named sign.jpg.
Image is missing .please help me to slove this. im new to android..
Here is my current code
public Bitmap save(View v) {
Log.v("log_tag", "Width: " + v.getWidth());
Log.v("log_tag", "Height: " + v.getHeight());
if (mBitmap == null) {
mBitmap = Bitmap.createBitmap(mContent.getWidth(),
mContent.getHeight(), Bitmap.Config.RGB_565);
}
Canvas canvas = new Canvas(mBitmap);
try {
FileOutputStream mFileOutStream = new FileOutputStream(mypath);
v.draw(canvas);
mBitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);
mFileOutStream.flush();
mFileOutStream.close();
String url = Images.Media.insertImage(getContentResolver(),
mBitmap, "title", null);
Log.v("log_tag", "url: " + url);
} catch (Exception e) {
Log.v("log_tag", e.toString());
}
return mBitmap;
}
Logcat displays this error message
09-16 17:11:52.517: E/BitmapFactory(1123): Unable to decode stream: java.io.FileNotFoundException: /storage/sdcard0/Captures/sign1945.jpg: open failed: EISDIR (Is a directory)
your problem is in mypath variable
-be sure to use Environment.getExternalStorageDirectory().getPath() to get the SD Card path
-you need to tell the compress method : hey i want to save bitmap to this directory with this name! like this:
//saveDirectoryPath = Environment.getExternalStorageDirectory().getPath() + "/folder/";
File file = new File(saveDirectoryPath);
if (!file.exists())
file.mkdir(); //or file.mkdirs(); depends on your need
File bitmapFile = new File(file, "yourImageFileName.jpg");
FileOutputStream mFileOutStream = new FileOutputStream(bitmapFile);
mBitmap.compress(CompressFormat.PNG, 90, mFileOutStream);

NullpointerException when trying to save the current Android app view as image

Hi StackOverflow community,
in my application I'd like to have a button which allows the user to capture the current view.
For that reason, I've written the following method (oriented towards: Android save view to jpg or png ):
private LinearLayout container;
public void createImageOfCurrentView(View v) {
if (isExternalStoragePresent()) {
container = (LinearLayout) findViewById(R.id.container);
container.setDrawingCacheEnabled(true);
Bitmap b = container.getDrawingCache();
File dir = new File(Environment.getExternalStorageDirectory().getPath()
+ "/" + getPackageName() + "/");
dir.mkdirs();
File file = new File(dir, "image.jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
b.compress(CompressFormat.JPEG, 95, fos); // NullPointerException!
Toast.makeText(this, "The current view has been succesfully saved "
+ "as image.", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
Toast.makeText(this, "Unfortunatly an error occured and this "
+ "action failed.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Bacause of lacking access to the storage "
+ "of this device, the current view couldn't be saved as an image.",
Toast.LENGTH_LONG).show();
}
}
The problem is according to LogCat that there occured a NullPointerException when trying to create the jpeg. So probably the method container.getDrawingCache() is not working. On the phone the file is generated. However with the size of 0 bytes and no visible image. I would appreciate any suggestions what I have to do in order to make it work as I want.
Try it -
public static Bitmap convertViewToBitmap(View view) {
Bitmap result = null;
try {
result = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.RGB_565);
view.draw(new Canvas(result));
}catch(Exception e) {}
return result;
}
Try it -
view.setDrawingCacheEnabled(true);
Bitmap = bm = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);

Categories

Resources