To save an image into the Android device's gallery, you can use the Android MediaStore API. Here's how you can do it:
import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.graphics.Bitmap; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class ImageSaver { public static Uri saveImageToGallery(Context context, Bitmap bitmap) { // Get the current timestamp to generate a unique file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()); // Define the image file name and location String imageFileName = "IMG_" + timeStamp + ".jpg"; File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); // Create a new file in the Pictures directory File imageFile = new File(storageDir, imageFileName); try { // Create a FileOutputStream to write the bitmap data to the file OutputStream fos = new FileOutputStream(imageFile); // Compress and save the bitmap to the file bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); // Close the FileOutputStream fos.close(); // Insert the image into the device's MediaStore so it appears in the gallery ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.TITLE, imageFileName); values.put(MediaStore.Images.Media.DESCRIPTION, "Image saved from my app"); values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); values.put(MediaStore.Images.Media.DATA, imageFile.getAbsolutePath()); ContentResolver contentResolver = context.getContentResolver(); Uri uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); return uri; } catch (Exception e) { e.printStackTrace(); return null; } } } In this code:
We generate a unique file name for the image using the current timestamp.
We define the image file name and location in the Pictures directory of the external storage.
We create a File object to represent the image file.
We create a FileOutputStream to write the bitmap data to the file.
We compress and save the bitmap to the file in JPEG format.
We close the FileOutputStream.
We insert the image into the MediaStore using the ContentValues and ContentResolver. This step is essential to make the image appear in the device's gallery.
Make sure you have the necessary permissions in your AndroidManifest.xml file to write to external storage:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Additionally, starting from Android 10 (API level 29), you need to request runtime permissions to write to external storage.
referenceerror lasagne uiactivityindicatorview inno-setup andengine postgresql-8.4 protractor-net bson tcpclient apache-pig