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;
}
Related
This question already has answers here:
Android permission doesn't work even if I have declared it
(11 answers)
Closed 4 years ago.
I want to store Bitmap image in external storage but I am getting an error creating the file directory.
This is my code.
private void saveImage(Bitmap bitmap){
String root = Environment.getExternalStorageDirectory().toString();
File directory = new File(root + "/Wallpapers");
boolean wasSuccessful = directory.mkdirs();
if(!wasSuccessful){
Toast.makeText(context, "Error Creating directory", Toast.LENGTH_SHORT).show();
}
Random generator = new Random();
int n = 10000;
n = generator.nextInt();
String fname = "Wallpaper-"+n+".png";
File file = new File(directory, fname);
if (file.exists()){
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Toast.makeText(context, "Wallpaper Saved Successfully", Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(context, "Error Saving Wallpaper", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
I already write the permission in android manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
I've already tried out many solutions but it cannot resolved my issue.
Writing simple example to store bitmapImage Image given as follows. please try it out ...
//Get file name and bitmapImage and call the method ()
//Bitmap bitmapImage = ImageUtil.getInstance().changeImageRotated(cameraUri, bitmapImage, ImageUtil.TypeMode.CAMERA);
//String fileName = String.valueOf(getCurrentTimeStamp());
//ImageUtil.getInstance().saveImage(bitmapImage, fileName);
//Here is function to save bitmap image to internal storage
public Boolean saveImage(Bitmap imageData, String fileName) {
String savePath = getFilePath(AppConst.getInstance().IMAGE_DIR_APPLY);
isPathMade(savePath);
File file = new File(savePath, fileName);
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
boolean keep = true;
try {
fileOutputStream = new FileOutputStream(file);
imageData.compress(Bitmap.CompressFormat.PNG, AppConst.getInstance().PARKING_APPLY_IMAGE_COMPRESS_QUALITY, fileOutputStream);
} catch (Exception e) {
keep = false;
} finally {
try {
if (objectOutputStream != null) {
objectOutputStream.close();
}
if (fileOutputStream != null){
fileOutputStream.close();
}
if (!keep) {
file.delete();
}
return true;
} catch (Exception e) {
Logger.e(TAG, "saveImageToCache Exception is " + e.toString());
}
}
return false;
}
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 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.
i'm trying to capture image with android native camera, the save image is good but doesnt contain the usual EXIF data (gps tags, orientation...)
what do i need to do to save also the EXIF?
#Override
public void onClick(View v) {
Intent takePictureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
imageuri = Uri.fromFile(photoFile);
startActivityForResult(takePictureIntent, CAMERA_PIC_REQUEST);
}
}
/*Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);*/
}
}
#SuppressLint("SimpleDateFormat")
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
Following is the method to Save an Image with EXIF Data (Location Data) to Gallery:
private String saveToGallery (Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to Directory
String photoDir = Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DCIM + "/";
File directory = new File(photoDir);
// Creates image file with the name "newimage.jpg"
File myfilepath = new File(directory, "newimage.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myfilepath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitgallery.compress(Bitmap.CompressFormat.JPEG, 80, fos);
fos.flush();
fos.close();
myfilepath.setReadable(true, false);
} catch (Exception e) {
e.printStackTrace();
}
Uri bitmapUri = Uri.fromFile(myfilepath);
String currentImageFile = bitmapUri.getPath();
//Writes Exif Information to the Image
try {
ExifInterfaceEx exif = new ExifInterfaceEx(currentImageFile);
Log.w("Location", String.valueOf(targetLocation));
exif.setLocation(targetLocation);
exif.saveAttributes();
} catch (Exception e) {
e.printStackTrace();
}
// Updating Gallery with the Image (Sending Broadcast to Gallery)
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentImageFile);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
return directory.getAbsolutePath();
}
The new image is not parsed, as it should be, by the MediaScanner. This smells like a device-specific bug.
See Image, saved to sdcard, doesn't appear in Android's Gallery app for workarounds.
Here is the function to save the Image,
public static String saveImageInExternalCacheDir(Context context, Bitmap bitmap, String myfileName) {
String fileName = myfileName.replace(' ', '_') + getCurrentDate().toString().replace(' ', '_').replace(":", "_");
String filePath = (context.getExternalCacheDir()).toString() + "/" + fileName + ".jpg";
try {
FileOutputStream fos = new FileOutputStream(new File(filePath));
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
}
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"/>