Android App using opencv: how to save an image without overwriting? - java

I'm using the following code to save an image to a folder when I select an option:
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String filename = "teste.png";
File file = new File(path, filename);
filename = file.toString();
Highgui.imwrite(filename, mRgba);
But i'd like the saved image to NOT OVERWRITE the image that's already in the folder. How could I do that? Using a kind of index for each image or something like that, I think, but how?
Thanks.

Maybe something like this?
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyAppDir");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.e(TAG, "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "testimage_" + timeStamp + ".png");

Related

Create a folder like WhatsApp Images, WhatsApp Videos in Albums or Gallery

My requirement is to show directory under Gallery/ Albums,
creating a directory in the following way does not full fill my requirement...
File rootPath = new File(Environment.getExternalStorageDirectory(), "directoryName");
if(!rootPath.exists()) {
rootPath.mkdirs();
}
final File localFile = new File(rootPath,fileName);
by using this code i can see the folder by using "file mangaer" with the path...
"deviceStorage/directoryName" but the folder is not visible under Gallery or Albums
for directory creation i tried the following ways too...
1)File directory = new File(this.getFilesDir()+File.separator+"directoryName");
2)File directory = new File (Environment.getExternalFilesDir(null) + "/directoryName/");
3)File directory = new File(Environment.
getExternalStoragePublicDirectory(
(Environment.DIRECTORY_PICTURES).toString() + "/directoryName");
but no luck, please help me friends
thanks in advance.
check this solution as well:
String path = Environment.getExternalStorageDirectory().toString();
File dir = new File(path, "/appname/media/app images/");
if (!dir.isDirectory()) {
dir.mkdirs();
}
File file = new File(dir, filename + ".jpg");
String imagePath = file.getAbsolutePath();
//scan the image so show up in album
MediaScannerConnection.scanFile(this,
new String[] { imagePath }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
if(Config.LOG_DEBUG_ENABLED) {
Log.d(Config.LOGTAG, "scanned : " + path);
}
}
});
Try this one.
File root = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + "albums");
boolean rootCreated = false;
if (!root.exists())
rootCreated = root.mkdir();
You can use MediaStore API to save your media files like that:
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, "filename")
put(MediaStore.Images.Media.RELATIVE_PATH, "${Environment.DIRECTORY_DCIM}/$directoryName")
put(MediaStore.Images.Media.MIME_TYPE, mimeType)
}
val collection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
val item = context.contentResolver.insert(collection, values) ?: throw IOException("Insert failed")
resolver.openFileDescriptor(item, "w", null)?.use {
writeImage(it.fileDescriptor)
}
This will save the media files to the media collections and make it available to the gallery. Gallery app normally shows your directoryName as an album.
Checked on Samsungs S10 and above with Android 10.
heres the java.nio library way to create directory
Java Code
File targetFile = new File(Environment.getExternalStorageDirectory(), "subDir");
Path sourceFile = Paths.get(targetFile.getAbsolutePath());
Files.createDirectory(sourceFile);
some android phone create .nomedia file inside the created app folder to prevent media from being shown in gallery app so you may check if this hidden file exists and delete it if it exists. set folder and files readable. you may wait quite time before system reflect your created file in your gallery app.
val parentFile = File(Environment.getExternalStorageDirectory(), "MyAppFolder")
if(!parentFile.exists())
parentFile.mkdir()
parentFile.setReadable(true)
// .nomedia file prevents media from being shown in gallery app
var nomedia = File(parentFile, ".nomedia")
if(nomedia.exists()){
nomedia.delete()
}
val file = File(parentFile , "myvideo.mp4")
file.setReadable(true)
input.use { input ->
var output: FileOutputStream? = null
try {
output = FileOutputStream(file)
val buffer = ByteArray(4 * 1024)
var read: Int = input.read(buffer)
while (read != -1) {
output.write(buffer)
read = input.read(buffer)
}
output.flush()
// file written to memory
} catch (ex: Exception) {
ex.printStackTrace()
} finally {
output?.close()
}
}

Is there a way to save to the gallery instead of the SD card?

I have this code here.
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "GIFName_" + System.currentTimeMillis() +".gif");
try{
FileOutputStream f = new FileOutputStream(file);
f.write(generateGIF(list));
}catch(Exception e){
e.printStackTrace();
}
my app basically converts images to .GIFS, and right now it saves it on the sd card, but I want to save it to gallery. Is there any way to do this easily? I know you can do it for images, but can you for .GIFS that are created?
Create folder in internal memory like this
File mydir = context.getDir("mydir", Context.MODE_PRIVATE);
File fileWithinMyDir = new File(mydir, "myfile");
FileOutputStream f = new FileOutputStream(fileWithinMyDir);
And than while saving file in the folder,give path to this directory.
Hope it helps!

FileNotFoundException - When creating a file and saving to external storage. - Android

I'm trying to save a file to external storage, however it's giving the FileNotFoundException error.
Note: I've already made the changes to Android Manifest.
File file = null;
if (isExternalStorageWritable()) {
Log.d("SEND", "Entrou no IF do ExernalStorage");
//File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File path = ContaListFragment.this.getActivity()
.getApplicationContext()
.getExternalFilesDir(
Environment.DIRECTORY_PICTURES);//getExternalFilesDir
file = new File(path, "file.json");
//Make sure the Pictures directory exists.
Log.d("SEND", "" + path.mkdir() + " PATH=" + file.getAbsolutePath());
//file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "file.json");
}
if (!file.mkdirs()) {
Log.d("SEND", "Directory not created");
}
if (!isExternalStorageWritable()) {
file = new File(ContaListFragment.this.getActivity()
.getApplicationContext().getFilesDir(), "file.json");
Log.d("SEND", "Passei do File");
output = new BufferedWriter(new FileWriter(file));
Log.d("SEND", "Passou do Buffered");
output.write(jsonObject.toString());
uri = Uri.fromFile(file);
}
The issue was resolved with the help of:
See the answers to this question
The problem was that I was creating a directory instead of a file. Just replace: file.mkdirs(); with file.createNewFile();

Uploaded image path from server

i uploaded an image from client to server...i need to save the server path in database...
i saved the image sucesssfully..i have a problem in path
I need to save the path like this in database
https://localhost/...../filename
but in mine the path was taken like this
d:/...../filename
this is my code
String root = request.getServletContext().getRealPath("/");
File path = new File(root + "/images/");
if (!path.exists())
{
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + vehicleId +".png");
String pathString=uploadedFile.getAbsolutePath();
item.write(uploadedFile);
Please sort out my problem..
thanking you..

Create a File in a folder

In Java, I have a File object representing a folder:
String folderName = "/home/vektor/folder";
File folder = new File(folderName);
Now I want to create another File representing a file in this folder. I want to avoid doing a string concatenation like this:
String fileName = "test.txt";
File file = new File(folderName + "/" + fileName);
Because if I go deeper in creating this structure, I will come up with something like this:
File deepFile = new File(folderName + "/" + anotherFolderName + ... + "/" + fileName);
I would instead like to do something like
File betterFile = folder.createUnder(fileName);
Or even:
File otherFile = SomeFileUtils.createFileInFolder(folder, fileName);
Do you know of such solution?
Note: It's quite OK to use "/" because Java will translate it to "\" for Windows, but it is not clean - I should use something like "file.separator" from System.getProperties().
Look at the Javadoc for File and you will see that the constructor takes a File object as parent.
Use the following form:
File deepFile = new File(folder, fileName);
I would use
String folderName =
String fileName =
File under = new File(folderName, fileName);
or
File folderFile =
String fileName =
File under = new File(folderFile, fileName);
simple as that ;)

Categories

Resources