При разработке Android эффективное хранение изображений имеет решающее значение для оптимизации производительности приложений и обеспечения удобства работы пользователей. Один из часто используемых подходов — сохранение изображений в таблице Mediastore.Images
. В этой статье рассматриваются различные методы хранения изображений в этой таблице, а также приводятся примеры кода. Используя эти методы, разработчики могут расширить возможности хранения изображений в своих приложениях для Android.
Метод 1: использование ContentResolver и ContentValues
private void saveImageUsingContentResolver(Bitmap bitmap, String title, String description) {
ContentResolver contentResolver = getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.TITLE, title);
contentValues.put(MediaStore.Images.Media.DESCRIPTION, description);
Uri imageUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
try {
OutputStream outputStream = contentResolver.openOutputStream(imageUri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Метод 2: использование MediaScannerConnection
private void saveImageUsingMediaScanner(Bitmap bitmap, String title, String description) {
String filePath = Environment.getExternalStorageDirectory().toString() + "/" + title;
try {
OutputStream outputStream = new FileOutputStream(filePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
MediaScannerConnection.scanFile(
this,
new String[]{filePath},
null,
null
);
} catch (IOException e) {
e.printStackTrace();
}
}
Метод 3: использование MediaStore.Images.Media API
private void saveImageUsingMediaStore(Bitmap bitmap, String title, String description) {
String imageFilePath = Environment.getExternalStorageDirectory().toString() + "/" + title + ".jpg";
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.TITLE, title);
contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, title);
contentValues.put(MediaStore.Images.Media.DESCRIPTION, description);
contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
contentValues.put(MediaStore.Images.Media.DATA, imageFilePath);
ContentResolver contentResolver = getContentResolver();
Uri imageUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
try {
OutputStream outputStream = contentResolver.openOutputStream(imageUri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Метод 4: использование FileProvider
private void saveImageUsingFileProvider(Bitmap bitmap, String title, String description) {
File imagePath = new File(getCacheDir(), "images");
if (!imagePath.exists()) {
imagePath.mkdirs();
}
File imageFile = new File(imagePath, title + ".jpg");
try {
OutputStream outputStream = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
Uri imageUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".fileprovider", imageFile);
grantUriPermission(getPackageName(), imageUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
MediaScannerConnection.scanFile(
this,
new String[]{imageFile.getAbsolutePath()},
null,
null
);
} catch (IOException e) {
e.printStackTrace();
}
}