I get a warning stating that the result of cachePath.createNewFile(); is ignored. Otherwise the following code does not save an image to my phone. What can I do?
holder.messageImage.setOnLongClickListener(v -> {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
Bitmap bitmap = ((BitmapDrawable) holder.messageImage.getDrawable()).getBitmap();
File root = Environment.getExternalStorageDirectory();
File cachePath = new File(root.getAbsolutePath() + "/DCIM/Camera/image.jpg");
try {
FileOutputStream ostream = new FileOutputStream(cachePath);
bitmap.compress(CompressFormat.JPEG, 100, ostream);
ostream.close();
Toast.makeText(mContext, "Image saved successfully", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Log.w(getClass().toString(), e);
Toast.makeText(mContext, "Failed saving image", Toast.LENGTH_SHORT).show();
}
return false;
});
I download the image from my back end this way:
private void downloadMessageImage(ViewHolder holder, int position) {
ParseQuery<ParseObject> query = new ParseQuery<>(ParseConstants.CLASS_YEET);
query.whereEqualTo(ParseConstants.KEY_OBJECT_ID, mYeets.get(position).getObjectId());
query.findInBackground((user, e) -> {
if (e == null) for (ParseObject userObject : user) {
if (userObject.getParseFile("image") != null) {
String imageURL = userObject.getParseFile("image").getUrl();
/*Log.w(getClass().toString(), imageURL);*/
if (imageURL != null) {
holder.messageImage.setVisibility(View.VISIBLE);
Picasso.with(mContext)
.load(imageURL)
.placeholder(R.color.placeholderblue)
.into(holder.messageImage);
} else {
holder.messageImage.setVisibility(View.GONE);
}
}
}
});
}
The bitmap certainly does not exist: android.graphics.Bitmap#12d9cc4
to save an image I use the following code:
try {
signature.setDrawingCacheEnabled(true);
Bitmap bm = Bitmap.createBitmap(signature.getDrawingCache());
// Define params for save
File f = new File(Environment.getExternalStorageDirectory() + "/Cassiopea/momomorez/" + File.separator + "signature.png");
f.createNewFile();
FileOutputStream os = new FileOutputStream(f);
os = new FileOutputStream(f);
//compress to specified format (PNG), quality - which is ignored for PNG, and out stream
bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Toast.makeText(mContext, "Saving image OK", Toast.LENGTH_SHORT).show();
os.close();
}
catch (Exception e) {
Log.v("Gestures", e.getMessage());
e.printStackTrace();
}
Use this code to save a pattern in an image within an established folder.
Related
I'm taking a screenshot of a dialog and trying to show the image into the gallery. I've saved the image into the external storage but the image is not visible into the gallery. When I go the storage location I can see the latest image there but the image is not showing into the gallery and I've tried multiple codes for this purpose but none work and there is no error as well. Can someone help me with this issue?
Below is the code I'm using to take a screenshot and trying to refresh the gallery:
public void showAlertDialog(final Activity activity) {
Dialog dialog = new Dialog(activity);
currentDialog = dialog;
currentActivity = activity;
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.payment_transaction_layout);
ImageView imageViewSS = dialog.findViewById(R.id.imageView19);
imageViewSS.setOnClickListener(v -> {
checkExternalStoragePermission(dialog);
});
dialog.show();
}
private void checkExternalStoragePermission(Dialog dialog) {
if (ContextCompat.checkSelfPermission(currentActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(currentActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_EXTERNAL_STORAGE);
} else {
Bitmap bitmap = takeScreenShot(dialog);
saveBitmap(bitmap);
}
}
private static Bitmap takeScreenShot(Dialog dialog) {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
// create bitmap screen capture
View v1 = dialog.getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
return bitmap;
}
public void saveBitmap(Bitmap bitmap) {
File imagePath = currentActivity.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File file = null;
try {
/**
*Creating file with the extension file name and given file name
* */
file = File.createTempFile(timeStamp, ".png", imagePath);
Log.e("location", "" + file.getAbsolutePath());
Log.e("TransferClass", "Clicked: " + fromWhere);
saveImageToGallery(bitmap, file);
} catch (IOException e) {
e.printStackTrace();
Log.e("TransferClass", "Exception caught: " + e.getMessage());
}
}
private void saveImageToGallery(Bitmap bitmap, File file) {
FileOutputStream fos;
try {
path = file.getAbsolutePath();
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Log.e("Screenshot", "saved successfully" + " Path " + path);
fos.flush();
fos.close();
//code for showing the image into gallery
currentActivity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(path)));
} catch (IOException e) {
}
}
This line solve my answer
MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, file.getName() ,file.getName());
Copied from Here:
android - save image into gallery
enter image description here
please someone help me "To save an image file with increment at end of file name" like("image 1.jpg , image 2.jpg , etc..")
here is my code
please some help me to make this,i am new learner to android-studio.
private File saveBitMap(Context context, View drawView) {
File pictureFileDir = new File(Environment.getExternalStorageDirectory()+"/"+"Frames");
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+"Frame"+ System.currentTimeMillis()+".jpg";
File pictureFile = new File(filename);
Bitmap bitmap =getBitmapFromView(drawView);
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;
}
If I have understood your question properly then, I assume you want your pictureFile name to be appended by an integer (in auto-incrementing fashion).
You could do that by maintaining a global variable as int imageCount = 1
and then appending it while creating fileName
int imageCount = 1;
private File saveBitMap(Context context, View drawView) {
File pictureFileDir = new File(Environment.getExternalStorageDirectory()+"/"+"Frames");
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+"Frame"+ System.currentTimeMillis()+""+(imageCount++)+".jpg";
File pictureFile = new File(filename);
Bitmap bitmap =getBitmapFromView(drawView);
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;
}
I have an Image in web server and load it to Image View using Picasso perfectly then save it to a folder in internal storage memory every thing is OK but the problem is the saved image size is 0 byte
here is my code
File newDir=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"km");
if (!newDir.exists()) {
if (!newDir.mkdirs()) {
Toast.makeText(this, "can not create directory", Toast.LENGTH_SHORT).show();
}
}
Picasso.with(this).load("http://192.168.1.101/cima/1.jpg").into(img);
File file = new File(new File("/storage/sdcard0/Download/km/"), "1.jpg");
img.buildDrawingCache();
Bitmap bmap = img.getDrawingCache();
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
bmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
any help for this issue ??
Try to below code
Picasso.with(getActivity())
.load(url)
.into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
try {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/yourDirectory");
if (!myDir.exists()) {
myDir.mkdirs();
}
String name = new Date().toString() + ".jpg";
myDir = new File(myDir, name);
FileOutputStream out = new FileOutputStream(myDir);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch(Exception e){
// some action
}
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
);
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.
To share the image via Email and mms first step I need to save the image in sdcard but for me the saved image is not getting opened instead "Invalid File" error, I checked with the extension format everything is correct but don't know where I'm going wrong.
Below is the java code.
public class Share extends CordovaPlugin {
public static final String ACTION_POSITION = "ShareImage";
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
throws JSONException {
if (ACTION_POSITION.equals(action)) {
try {
JSONObject arg_object = args.getJSONObject(0);
Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
sendIntent.setType("image/jpg");
sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, arg_object.getString("image"));
String name = arg_object.getString("image");
String defType = "drawable";
String defPackage = "com.picsswipe";
int drawableId = this.cordova.getActivity().getResources().getIdentifier( name , defType, defPackage );
// Bitmap bbicon = BitmapFactory.decodeFile( arg_object.getString("image") );
Bitmap bbicon = BitmapFactory.decodeResource( this.cordova.getActivity().getResources(),drawableId );
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File f = new File(extStorageDirectory + "/Download/",
"jj.jpg" );
try {
outStream = new FileOutputStream(f);
bbicon.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
}
File r1 = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Download/", "jj.jpg");
//RETRIEVING IMAGES FROM SDCARD
Uri uri1 = Uri.fromFile(r1);
sendIntent.putExtra(Intent.EXTRA_STREAM, uri1);
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(r1));
Uri uris = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "jj.jpg"));
this.cordova.getActivity().startActivity(sendIntent);
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
callbackContext.error(e.getMessage());
return false;
}
}
return true;
}
}
File file;
File rootPath = android.os.Environment
.getExternalStorageDirectory();
File directory = new File(rootPath.getAbsolutePath()
+ "/Download");
if (!directory.exists())
directory.mkdir();
file = new File(directory, "filename.PNG");//.png/.jpg anything you want
try {
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.pincheck);
FileOutputStream outStream;
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and you should add this permission in your manifest file..Then only file will copied to your external sd card.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>