我需要将图像保存到camera文件夹,但是由于不赞成使用Android Q getExternalStoragePublicDirectory,因此我以另一种方式进行操作。 我有什么(此方法接收位图及其名称):
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = mContext.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM/" + IMAGES_FOLDER_NAME);
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
OutputStream fos = resolver.openOutputStream(imageUri);
saved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} else {
String imagesDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM).toString() + File.separator + IMAGES_FOLDER_NAME;
File file = new File(imagesDir);
if (!file.exists()) {
file.mkdir();
}
File image = new File(
imagesDir,
name + ".png"
);
final long fileHashCode = image.hashCode();
Logger.d(TAG, "saveImage, saving image file, hashCode = " + fileHashCode);
FileOutputStream fos = new FileOutputStream(image);
saved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}
这对于所有所需的OS版本都可以完美地工作,但是它看起来不准确,我想找到一种更通用的方法。 我尝试使用内容值或尝试一些与Q相似的方法,但是它不起作用。我在这里看到了很多问题,但是它们都不能帮助我。
问题是如何针对低于Q的操作系统优化保存?
答案 0 :(得分:7)
我能写的最通用的版本是:
private void saveImage(Bitmap bitmap, @NonNull String name) throws IOException {
boolean saved;
OutputStream fos;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = mContext.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM/" + IMAGES_FOLDER_NAME);
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
fos = resolver.openOutputStream(imageUri);
} else {
String imagesDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM).toString() + File.separator + IMAGES_FOLDER_NAME;
File file = new File(imagesDir);
if (!file.exists()) {
file.mkdir();
}
File image = new File(imagesDir, name + ".png");
fos = new FileOutputStream(image)
}
saved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}
如果您找到了更好的方法,请在此处发布,我将其标记为答案。
答案 1 :(得分:1)
使用本文档:https://developer.android.com/training/data-storage
<块引用>先创建临时文件
val mTempFileRandom = Random()
fun createTempFile(ext:String, context:Context):String {
val path = File(context.getExternalCacheDir(), "AppFolderName")
if (!path.exists() && !path.mkdirs())
{
path = context.getExternalCacheDir()
}
val result:File
do
{
val value = Math.abs(mTempFileRandom.nextInt())
result = File(path, "AppFolderName-" + value + "-" + ext)
}
while (result.exists())
return result.getAbsolutePath()
}
<块引用>
从路径发送文件
copyFileToDownloads(this@CameraNewActivity, File(savedUri.path))
<块引用>
复制数据到存储
<块引用>MAIN_DIR:您要存储图像的主文件夹名称(如应用程序名称) IMAGE_DIR:如果要创建子文件夹。
fun copyFileToDownloads(context: Context, downloadedFile: File): Uri? {
// Create an image file name
val timeStamp = SimpleDateFormat(DATE_FORMAT_SAVE_IMAGE).format(Date())
val imageFileName = "JPEG_$timeStamp.jpg"
val resolver = context.contentResolver
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, imageFileName)
put(MediaStore.Images.Media.MIME_TYPE, IMAGE_MIME_TYPE)
put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_DCIM + File.separator + MAIN_DIR + File.separator + IMAGE_DIR + File.separator)
}
resolver.run {
val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
uri
}
} else {
val authority = "${context.packageName}.provider"
val imagePath =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)?.absolutePath
val destinyFile = File(imagePath, imageFileName)
val uri = FileProvider.getUriForFile(context, authority, destinyFile)
FileUtils.scanFile(context, destinyFile.absolutePath)
uri
}?.also { uri ->
var writtenValue = 0L
// Opening an outputstream with the Uri that we got
resolver.openOutputStream(uri)?.use { outputStream ->
downloadedFile.inputStream().use { inputStream ->
writtenValue = inputStream.copyTo(outputStream)
Log.d("Copy Written flag", " = $writtenValue")
}
}
}
}
<块引用>
扫描文件:(更多细节:https://developer.android.com/reference/android/media/MediaScannerConnection)
fun scanFile(context:Context, path:String) {
MediaScannerConnection.scanFile(context,
arrayOf<String>(path), null,
{ newPath, uri-> if (BuildConfig.DEBUG)
Log.e("TAG", "Finished scanning " + newPath) })
}
答案 2 :(得分:0)
我们不能在 Android Q 之上和之下使用媒体商店吗? 我试过以下方法,效果很好。
private fun writeImage() {
val uri =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
} else {
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
}
val imageDetail = ContentValues().apply {
put(MediaStore.Images.ImageColumns.DISPLAY_NAME, "${System.currentTimeMillis()}.jpeg")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
put(MediaStore.Images.Media.IS_PENDING, 1)
}
}
val contentUri = contentResolver.insert(uri, imageDetail)
contentUri?.let {
contentResolver.openFileDescriptor(contentUri, "w", null).use { pd ->
pd?.let {
/* val fos = FileOutputStream(it.fileDescriptor)
val array = getBitmapToBase64()
fos.write(array, 0, array.size)
fos.close()
*/
// or
// Your logic to write an Image file.
}
}
imageDetail.clear()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
imageDetail.put(MediaStore.Images.Media.IS_PENDING, 0)
contentUri.let { contentResolver.update(it, imageDetail, null, null) }
}
// open the saved image file with gallery app
Snackbar.make(
findViewById(android.R.id.content), "saved", Snackbar.LENGTH_LONG
).setAction("Show") {
val intent = Intent(Intent.ACTION_VIEW, contentUri)
startActivity(intent)
}.show()
} ?: Toast.makeText(this, "not saved", Toast.LENGTH_LONG).show()
}