Android - Save Images in an Specific Folder

Android - Save images in an specific folder

Go through the following code , its working fine for me.

private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) {

File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");

if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/DirName/");
wallpaperDirectory.mkdirs();
}

File file = new File("/sdcard/DirName/", fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}

How to Save images in an specific folder android

try this

addToFav("/Favorite", "add to favoriote");

create this function

    public void addToFav(String dirName, String str) {

String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
String fileName = "fav" + timeStamp + ".JPG";

File direct = new File(Environment.getExternalStorageDirectory() + dirName);

if (!direct.exists()) {
File wallpaperDirectory = new File(Environment.getExternalStorageDirectory() + dirName);
wallpaperDirectory.mkdirs();
}

File file = new File(new File(Environment.getExternalStorageDirectory() + dirName), fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);

Bitmap bitmap = BitmapFactory.decodeFile(imagesPathArrayList.get(pos));
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}

ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "title");
values.put(Images.Media.DESCRIPTION, "description");
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.ImageColumns.BUCKET_ID, file.toString().toLowerCase(Locale.US).hashCode());
values.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, file.getName().toLowerCase(Locale.US));
values.put("_data", file.getAbsolutePath());
ContentResolver cr = getContentResolver();
cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

}

and don't forget to add permission in manifest file

Save image in specific folder in android device

This should do it:

private void createDirectoryAndSaveFile(Bitmap imgSave, String fileName) {

File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");

if (!direct.exists()) {
File imageDirectory = new File("/sdcard/DirName/");
imageDirectory.mkdirs();
}

File file = new File(new File("/sdcard/DirName/"), fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imgSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}

How do I save images in storage particular folder (gallery) & Get image from storage in above android 11 or below with java?

Hi First add below line to manifest in application tab

for make directory in android 10 & solve error in android 8

<application
android:requestLegacyExternalStorage="true"
android:hardwareAccelerated="false"
android:largeHeap="true" />

& than try below code / method

in blank space set folder name of your wish and put this in res - values - string

<resources>
<string name="app_folder_name">Your_Folder_name</string>
</resources>

Then add this method to your Activity.

private void saveToGallery() {
String parentPath="";
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// for above android 11
parentPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + Environment.DIRECTORY_PICTURES + File.separator + getString(R.string.app_folder_name);
}else{
// for below android 11
parentPath = Environment.getExternalStorageDirectory() + File.separator + getString(R.string.app_folder_name);
}
File parentFile = new File(parentPath);
Log.e("TAG", "saveToGallery1: "+parentFile);
if (!parentFile.exists()){
parentFile.mkdirs();
}
File imageFile = new File(parentFile, "drawing"+System.currentTimeMillis() + ".png"); // Imagename.png

FileOutputStream out = null;
try {
out = new FileOutputStream(imageFile);
Bitmap bmp = binding.paintView.save();
Common.DRAWING_BITMAP = bmp;
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // Compress Image
out.flush();
out.close();
// Tell the media scanner about the new file so that it is // immediately available to the user.
MediaScannerConnection.scanFile(PaintDrawActivity.this, new String[]{imageFile.getAbsolutePath()}, null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.e("ExternalStorage1", "Scanned " + path + ":");
Log.e("ExternalStorage1", "-> uri=" + uri);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}

private void getMyWorkImagesFromStorage() {
File file;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// for above android 11
file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), Environment.DIRECTORY_PICTURES + File.separator + getString(R.string.app_folder_name));
} else {
// for below android 11
file = new File(Environment.getExternalStorageDirectory() + File.separator + getString(R.string.app_folder_name));
}
File[] files = file.listFiles();
if (files != null) {
for (File file1 : files) {
if (file1.getPath().endsWith(".png") || file1.getPath().endsWith(".jpg")) {
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(file1.getAbsolutePath(), bmOptions);

myWorkItems.add(new MyGalleryItem(bitmap, file1.getName()));
Common.MY_GALLERY_IMAGES = myWorkItems;
}
}
if (files.length == 0) {
binding.tvEmpty.setVisibility(View.VISIBLE);
} else {
binding.tvEmpty.setVisibility(View.GONE);
}
}
}

How to list images from a specific folder

Try using the following function for the same :
First declare a const variable with the name of the folder that you want to search for :

const val TESTAPP = "TestApp"

And then use the following function to get data

override suspend fun getData(): List<UserWork>? =

withContext(Dispatchers.IO) {
try {

val collection = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL)
} ?: MediaStore.Images.Media.EXTERNAL_CONTENT_URI

val selection =
MediaStore.Images.ImageColumns.RELATIVE_PATH + " like ? "
val projection = arrayOf(
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.Images.Media.RELATIVE_PATH,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
MediaStore.Images.Media.BUCKET_ID,
MediaStore.MediaColumns.WIDTH
)

val selectionArgs = arrayOf("%$TESTAPP%")

val sortOrder = MediaStore.MediaColumns.DATE_ADDED + " COLLATE NOCASE DESC"

val itemList: MutableList<UserWork> = mutableListOf()

context.contentResolver?.query(
collection,
projection,
selection,
selectionArgs,
sortOrder
)?.use { cursor ->

val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
val displayNameColumn =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)
val relativePathColumn =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.RELATIVE_PATH)
val widthPathColumn =
cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.WIDTH)

while (cursor.moveToNext()) {
val id = cursor.getLong(idColumn)
val displayName = cursor.getString(displayNameColumn)
val relativePath = cursor.getString(relativePathColumn)
val width = cursor.getInt(widthPathColumn)

val contentUri = ContentUris.withAppendedId(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id
)

itemList.add(UserWork(id, displayName, contentUri))

}
cursor.close()
}

itemList
} catch (e: Exception) {
Log.d(
"MediaStoreException", "The exception for getData is " +
"$e"
)
null
}

}



Related Topics



Leave a reply



Submit