how to save the text of the activity in an image? - java

I need get the text that is in view, and save the image format. I need store the image in the external memory of device.
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.text);
}
}

I use this solution
public void saveScreenshotOnDisk (final View view, final Context context, final String folder, final String title, final String description) {
final String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
final Bitmap screenshot = screenShot(view, context);
final File folderPath = new File(Environment.getExternalStorageDirectory().toString() + File.separatorChar + folder + File.separatorChar + "" + "s");
if (!folderPath.exists()) {
folderPath.mkdirs();
}
final String imagePath = folderPath.getAbsolutePath() + File.separatorChar + "Receipt" + "_" + System.currentTimeMillis() + ".png";
OutputStream fout = null;
File imageFile = new File(imagePath);
try {
fout = new FileOutputStream(imageFile);
screenshot.compress(Bitmap.CompressFormat.JPEG, 90, fout);
MediaStore.Images.Media.insertImage(context.getContentResolver(), screenshot, title, description);
Toast.makeText(context, "Verifique a pasta " + folder + " .", Toast.LENGTH_LONG).show();
} catch (Exception e) {
BBLog.w(TAG + ".saveScreenshotOnDisk", e.getMessage());
}finally{
try {
if(fout != null){
fout.flush();
fout.close();
}
} catch (Exception e2) {}
}
}
}
public static Bitmap screenShot(final View view, final Context context) {
view.setBackgroundColor(Color.WHITE);
Bitmap capture = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(capture);
view.draw(c);
view.setBackgroundColor(Color.TRANSPARENT);
shootSound(context);
return capture;
}

I personally use this:
public static Bitmap fromView(#NonNull final View view) {
final DisplayMetrics displayMetrics = ApplicationHelper.resources().getDisplayMetrics();
if (displayMetrics == null) {
LogHelper.warning("DisplayMetrics was NULL");
return null;
}
view.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
view.buildDrawingCache();
final Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
This method returns a Bitmap of any View, just like a screenshot (of a View).
You can then store or upload this Bitmap as a proof.

Related

How to take a screenshot on Android?

I am trying to take a screenshot using the code below, I click the button takeScreenshot() is attached to but nothing happens.
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, first create class:
public class TakeScreenshot {
public static Bitmap takescreenshot(View view) {
view.setDrawingCacheEnabled(true);
view.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return b;
}
public static Bitmap takescreenshotofview(View view) {
return takescreenshot(view.getRootView());
}}
And in MainActivity:
public void onClick(View view) {
Bitmap b = TakeScreenshot.takescreenshotview(imageView);
imageView.setImageBitmap(b);
}

CursorAdapter with images are loading weird

I have a simple CursorAdapter that gets a title and image.
It shows the title and then loads the image from the Internet.
However, when I call the image loader the image is loaded at the wrong place, and it starts going really wild: see here.
My complete code is here.
The adapter is RestaurantListActivityCursorAdapter
public class RestaurantListActivityCursorAdapter extends CursorAdapter {
/* Api variables */
String websiteURL = "http://cicolife.com";
public RestaurantListActivityCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.activity_main_list_item, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// Extract properties from cursor
int get_Id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
String getTitle = cursor.getString(cursor.getColumnIndexOrThrow("title"));
String getImage = cursor.getString(cursor.getColumnIndexOrThrow("image"));
// Name
TextView listViewTitle = (TextView) view.findViewById(R.id.listViewTitle);
listViewTitle.setText(getTitle);
// Img
ImageView listViewImage = (ImageView) view.findViewById(R.id.listViewImage);
if(getImage != null) {
if (!(getImage.equals(""))) {
String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+ File.separatorChar+"/Android/data/com.nettport.restaurants/imgs";
File file = new File (destinationPath, getImage);
if (file.exists ()){
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
listViewImage.setImageBitmap(myBitmap);
}
else {
String loadImage = websiteURL + "/_cache/" + getImage;
new HttpRequestImageLoadTask(context, loadImage, listViewImage, getImage,"imgs").execute();
}
}
}
}
}
The image loader HttpRequestImageLoadTask
public class HttpRequestImageLoadTask extends AsyncTask<Void, Void, Bitmap> {
private String url;
private ImageView imageView;
private LinearLayout linearLayout;
private Resources resources;
private Context context;
private String storeDirectory;
private String imageName;
public interface TaskListener {
void onFinished(String result);
}
public HttpRequestImageLoadTask(Context ctx, String url, ImageView imageView, String imgName, String storeDirectory) {
this.context = ctx;
this.url = url;
this.imageView = imageView;
this.imageName = imgName;
this.storeDirectory = storeDirectory;
}
public HttpRequestImageLoadTask(Context ctx, String url, LinearLayout linearLayout, Resources resources, String imgName, String storeDirectory) {
this.context = ctx;
this.url = url;
this.linearLayout = linearLayout;
this.imageName = imgName;
this.storeDirectory = storeDirectory;
}
#Override
protected Bitmap doInBackground(Void... params) {
if (checkIfCacheExists(imageName)) {
String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data/com.nettport.restaurants/" + storeDirectory;
File file = new File (destinationPath, imageName);
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
return myBitmap;
} else {
try {
URL urlConnection = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
saveImage(myBitmap);
return myBitmap;
} catch(Exception e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if(imageView != null) {
imageView.setImageBitmap(result);
} else {
if(linearLayout != null){
BitmapDrawable background = new BitmapDrawable(resources, result);
linearLayout.setBackground(background);
}
}
}
public boolean checkIfCacheExists(String imgName){
String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data/com.nettport.restaurants/" + storeDirectory;
File file = new File (destinationPath, imgName);
return file.exists();
}
private void saveImage(Bitmap finalBitmap) {
// Make dir
String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data/com.nettport.restaurants/" + storeDirectory;
File folder = new File(destinationPath);
try {
if (!folder.exists()) {
// Make Android
destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android";
folder = new File(destinationPath);
if (!folder.exists()) {
folder.mkdir();
}
// Make Android/data
destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data";
folder = new File(destinationPath);
if (!folder.exists()) {
folder.mkdir();
}
// Make Android/data/com.nettport.restaurants
destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data/com.nettport.restaurants";
folder = new File(destinationPath);
if (!folder.exists()) {
folder.mkdir();
}
// Make Android/data/com.nettport.restaurants/storeDirectory
destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data/com.nettport.restaurants/" + storeDirectory;
folder = new File(destinationPath);
if (!folder.exists()) {
folder.mkdir();
}
}
} catch (Exception e){
Toast.makeText(context, "Could not create directory:\n" + e.toString(), Toast.LENGTH_LONG).show();
}
if(imageName != null) {
File file = new File(destinationPath, imageName);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
// Toast.makeText(context, "Cant save image\n" + e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
You have not put any else condition for your ImageView in your adapter. I see there are several else blocks are missing here.
if(getImage != null) {
if (!(getImage.equals(""))) {
String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+ File.separatorChar+"/Android/data/com.nettport.restaurants/imgs";
File file = new File (destinationPath, getImage);
if (file.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
listViewImage.setImageBitmap(myBitmap);
} else {
String loadImage = websiteURL + "/_cache/" + getImage;
// Add nothing here when the image is being fetched
listViewImage.setImageBitmap(null);
new HttpRequestImageLoadTask(context, loadImage, listViewImage, getImage,"imgs").execute();
}
} else {
// Add an else block here when image is equals ""
listViewImage.setImageBitmap(null);
}
} else {
// Add an else block here when image is null
listViewImage.setImageBitmap(null);
}
You need to specify every possible combination in your adapter while loading the images in your ImageView.
And if you have the image url from server, just use Glide to load the images when they are not available in cache.

How to get image from camera from fragment in Android

In my code I got null on bitmap but Image created successfully and uri is fine but BitmapFactory.decodeFile() return null.
I used fragment below code:
public class CameraImage extends Fragment {
private static final int TAKE_PHOTO_CODE = 1888;
Button button;
private Uri fileUri1,fileUri;
ImageView imageView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.camera_image,
container, false);
button = (Button) rootView.findViewById(R.id.button);
imageView = (ImageView) rootView.findViewById(R.id.imageview);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
fileUri1 = getOutputMediaFileUri();
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
});
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PHOTO_CODE) {
if (resultCode == Activity.RESULT_OK) {
BitmapFactory.Options options;
try {
Bitmap bitmap = BitmapFactory.decodeFile(pathname);
showDialog(bitmap, 1);
} catch (OutOfMemoryError e) {
try {
options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bitmap = BitmapFactory.decodeFile(pathname, options);
imageView.setImageBitmap(bitmap);
} catch (Exception e2) {
Log.e("Camera", "" + e2 + " " + e);
}
}
}
}
} }
public Uri getOutputMediaFileUri() {
return Uri.fromFile(getOutputMediaFile());
}
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(MyApplication.getAppContext().getFilesDir().getAbsolutePath()),
IMAGE_DIRECTORY_NAME);
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
try {
mediaFile = File.createTempFile(
"IMG_" + timeStamp,
".jpg",
mediaStorageDir
);
} catch (Exception e) {
Log.e("Camera", "" + e);
mediaFile = new File(mediaStorageDir.getPath() + File.separator
, "IMG_" + timeStamp + ".jpg");
}
return mediaFile;
}
In above code I got null on bitmap in onActivityResult but I got uri from this image is present at that location.
there are two types of image we can get via camera:
1) thumbnail image by using below code in onActivityResult:
Bitmap photo = (Bitmap) data.getExtras().get("data");
Log.i(TAG, "" + photo + " / " + data.getExtras().get("data") + " / " + data.getData());
showDialog(photo, 1);
2) full quality immage by using below code in onActivityResult:
BitmapFactory.Options options;
options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bitmap = BitmapFactory.decodeFile(pathname, options);
showDialog(bitmap, 1);
3) use third party easy and comfortable:
compile 'com.mindorks:paracamera:0.2.2'
paracamera github
I solved my question:
by changing cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
to
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri1);

'TAG' has private access in 'android.support.v4.app.FragmentActivity'

Almost everything in my activity is working fine, except for wherever TAG is referenced. TAG gets a red line and says: 'TAG' has private access in 'android.support.v4.app.FragmentActivity'.
MainActivity (without imports)-
public class MainActivity extends AppCompatActivity {
public static final String DATA_PATH = Environment
.getExternalStorageDirectory().toString() + "/MainActivity";
public static final String lang = "eng";
protected Button _button;
protected ImageView _image;
protected TextView _field;
protected String _path;
protected boolean _taken;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] paths = new String[] { DATA_PATH, DATA_PATH + "tessdata/" };
for (String path : paths) {
File dir = new File(path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.v(TAG, "ERROR: Creation of directory " + path + " on sdcard failed");
return;
} else {
Log.v(TAG, "Created directory " + path + " on sdcard");
}
}
}
if (!(new File(DATA_PATH + "tessdata/" + lang + ".traineddata")).exists()) {
try {
AssetManager assetManager = getAssets();
InputStream in = assetManager.open("tessdata/" + lang + ".traineddata");
//GZIPInputStream gin = new GZIPInputStream(in);
OutputStream out = new FileOutputStream(DATA_PATH
+ "tessdata/" + lang + ".traineddata");
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
//while ((lenf = gin.read(buff)) > 0) {
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
//gin.close();
out.close();
Log.v(TAG, "Copied " + lang + " traineddata");
} catch (IOException e) {
Log.e(TAG, "Was unable to copy " + lang + " traineddata " + e.toString());
}
}
_image = ( ImageView ) findViewById( R.id.image );
_field = ( TextView ) findViewById( R.id.field );
_button = ( Button ) findViewById( R.id.button );
_button.setOnClickListener( new ButtonClickHandler() );
_path = Environment.getExternalStorageDirectory() + "/Login Data.jpg";
}
public class ButtonClickHandler implements View.OnClickListener
{
public void onClick( View view ){
startCameraActivity();
}
}
protected void startCameraActivity()
{
File file = new File( _path );
Uri outputFileUri = Uri.fromFile( file );
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );
startActivityForResult( intent, 0 );
}
protected void onPhotoTaken()
{
_taken = true;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile( _path, options );
_image.setImageBitmap(bitmap);
_field.setVisibility( View.GONE );
ExifInterface exif = new ExifInterface(_path);
int exifOrientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
int rotate = 0;
switch (exifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
}
if (rotate != 0) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
// Setting pre rotate
Matrix mtx = new Matrix();
mtx.preRotate(rotate);
// Rotating Bitmap & convert to ARGB_8888, required by tess
bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
}
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.init(DATA_PATH, lang);
baseApi.setImage(bitmap);
String recognizedText = baseApi.getUTF8Text();
baseApi.end();
}
#Override
protected void onSaveInstanceState( Bundle outState ) {
outState.putBoolean( MainActivity.PHOTO_TAKEN, _taken );
}
#Override
protected void onRestoreInstanceState( Bundle savedInstanceState)
{
Log.i( "MakeMachine", "onRestoreInstanceState()");
if( savedInstanceState.getBoolean( MainActivity.PHOTO_TAKEN ) ) {
onPhotoTaken();
}
}
You should define a constant for your tag in MainActivity:
private static final String TAG = "MainActivity"
try the following
private static final String TAG = MainActivity.class.getSimpleName();
You can use this field in your any Activity or Fragment.
Well that's just an Android's way of telling us that we haven't defined TAG. To define the TAG in the current file, we can go to MainActivity Class and type "logt", you will get some auto code suggestions from Android studio, press enter there and you will get following code
private static final String TAG = "MainActivity";
Once you add this to your code, your error will be gone
Practical note: following is the better approach
private static final String TAG = MainActivity.class.getSimpleName();
as compared to:
private static final String TAG = "MainActivity";

Screenshot Black in Android

I've been working out how to take a screenshot programmatically in android, however when it screenshots I get a toolbar and black screen captured instead of what is actually on the screen.
I've also tried to screenshot a particular TextView within the custom InfoWindow layout I created for the google map. But that creates a null pointer exception on the second line below.
TextView v1 = (TextView)findViewById(R.id.tv_code);
v1.setDrawingCacheEnabled(true);
Is there anyway to either actually screenshot what is on the screen without installing android screenshot library or to screenshot a TextView within a custom InfoWindow layout
This is my screenshot method:
/**
* Method to take a screenshot programmatically
*/
private void takeScreenshot(){
try {
//TextView I could screenshot instead of the whole screen:
//TextView v1 = (TextView)findViewById(R.id.tv_code);
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg");
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
MediaStore.Images.Media.insertImage(getContentResolver(), f.getAbsolutePath(), f.getName(), f.getName());
Log.d("debug", "Screenshot saved to gallery");
Toast.makeText(HuntActivity.this,"Code Saved!",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
EDIT: I have changed the method to the one provided from the source
How can i take/merge screen shot of Google map v2 and layout of xml both programmatically?
However it does not screenshot anything.
public void captureMapScreen() {
GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback() {
#Override
public void onSnapshotReady(Bitmap snapshot) {
try {
View mView = getWindow().getDecorView().getRootView();
mView.setDrawingCacheEnabled(true);
Bitmap backBitmap = mView.getDrawingCache();
Bitmap bmOverlay = Bitmap.createBitmap(
backBitmap.getWidth(), backBitmap.getHeight(),
backBitmap.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(backBitmap, 0, 0, null);
canvas.drawBitmap(snapshot, new Matrix(), null);
FileOutputStream out = new FileOutputStream(
Environment.getExternalStorageDirectory()
+ "/"
+ System.currentTimeMillis() + ".jpg");
bmOverlay.compress(Bitmap.CompressFormat.JPEG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
};
mMap.snapshot(callback);
}
Use this code
private void takeScreenshot() {
AsyncTask<Void, Void, Void> asyc = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
objUsefullData.showProgress("Please wait", "");
}
#Override
protected Void doInBackground(Void... params) {
try {
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
bitmapscreen_shot = Bitmap.createBitmap(v1
.getDrawingCache());
v1.setDrawingCacheEnabled(false);
String state = Environment.getExternalStorageState();
File folder = null;
if (state.contains(Environment.MEDIA_MOUNTED)) {
folder = new File(
Environment.getExternalStorageDirectory()
+ "/piccapella");
} else {
folder = new File(
Environment.getExternalStorageDirectory()
+ "/piccapella");
}
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
// Create a media file name
String timeStamp = new SimpleDateFormat(
"yyyyMMdd_HHmmss", Locale.getDefault())
.format(new java.util.Date());
imageFile = new File(folder.getAbsolutePath()
+ File.separator + "IMG_" + timeStamp + ".jpg");
/*
* Toast.makeText(AddTextActivity.this,
* "saved Image path" + "" + imageFile,
* Toast.LENGTH_SHORT) .show();
*/
imageFile.createNewFile();
} else {
/*
* Toast.makeText(AddTextActivity.this,
* "Image Not saved", Toast.LENGTH_SHORT).show();
*/
}
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
// save image into gallery
bitmapscreen_shot.compress(CompressFormat.JPEG, 100,
ostream);
FileOutputStream fout = new FileOutputStream(imageFile);
fout.write(ostream.toByteArray());
fout.close();
Log.e("image_screen_shot", "" + imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
objUsefullData.dismissProgress();
}
};
asyc.execute();
}
Hope this will help you
I have figured it out !
/**
* Method to take a screenshot programmatically
*/
private void takeScreenshot(){
GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback() {
#Override
public void onSnapshotReady(Bitmap bitmap) {
Bitmap b = bitmap;
String timeStamp = new SimpleDateFormat(
"yyyyMMdd_HHmmss", Locale.getDefault())
.format(new java.util.Date());
String filepath = timeStamp + ".jpg";
try{
OutputStream fout = null;
fout = openFileOutput(filepath,MODE_WORLD_READABLE);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
saveImage(filepath);
}
};
mMap.snapshot(callback);
}
/**
* Method to save the screenshot image
* #param filePath the file path
*/
public void saveImage(String filePath)
{
File file = this.getFileStreamPath(filePath);
if(!filePath.equals(""))
{
final ContentValues values = new ContentValues(2);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
final Uri contentUriFile = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Toast.makeText(HuntActivity.this,"Code Saved to files!",Toast.LENGTH_LONG).show();
}
else
{
System.out.println("ERROR");
}
}
I have adapted the code from this link so it doesn't share and instead just saves the image.
Capture screen shot of GoogleMap Android API V2
Thanks for everyones help
Please try with the code below:
private void takeScreenshot(){
try {
//TextView I could screenshot instead of the whole screen:
//TextView v1 = (TextView)findViewById(R.id.tv_code);
Bitmap bitmap = null;
Bitmap bitmap1 = null;
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
try {
if (bitmap != null)
bitmap1 = Bitmap.createBitmap(bitmap, 0, 0,
v1.getWidth(), v1.getHeight());
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
v1.setDrawingCacheEnabled(false);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg");
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
MediaStore.Images.Media.insertImage(getContentResolver(), f.getAbsolutePath(), f.getName(), f.getName());
Log.d("debug", "Screenshot saved to gallery");
Toast.makeText(HuntActivity.this,"Code Saved!",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I faced this issue. After v1.setDrawingCacheEnabled(true); I added,
v1.buildDrawingCache();
And put some delay to call the takeScreenshot(); method.
It is fixed.

Categories