Доступ к изображениям во внешнем хранилище, созданным моим приложением ⇐ Android
Доступ к изображениям во внешнем хранилище, созданным моим приложением
I need a method to access the images stored in external storage by my app.
I want to access those images without requesting READ_EXTERNAL_STORAGE or READ_MEDIA_IMAGES from the user
I'm using ACTION_GET_CONTENT to get the image from the user.
val launcher = rememberLauncherForActivityResult(contract = ActivityResultContracts.StartActivityForResult()){ val uri : String = it.data?.data?.toString()?:"null" if (uri != "null"){ val mimeType = context.contentResolver.getType(uri.toUri()).toString() it.data?.data?.let { returnUri -> context.contentResolver.query(returnUri, null, null, null, null) }?.use { cursor -> val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE) cursor.moveToFirst() val name = cursor.getString(nameIndex) val size = cursor.getLong(sizeIndex) image = image.copy( path = uri, mimeType = mimeType.replace("image/",""), size = size, name = name, uri = it.data?.data ) } }else{ image = image.copy(path = uri) } } Calling the launcher for result
launcher.launch(Intent(Intent.ACTION_GET_CONTENT).setType("image/*")) After performing the required actions on the image, I save the image using the following method.
fun saveFile(context : Context, file: File) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){ try { val values = ContentValues() val path = Environment.DIRECTORY_PICTURES + "/FolderName" values.put(MediaStore.MediaColumns.DISPLAY_NAME, file.name) values.put(MediaStore.MediaColumns.MIME_TYPE, "image/*") values.put(MediaStore.MediaColumns.RELATIVE_PATH, path) val savedFile = context.contentResolver.insert(Media.EXTERNAL_CONTENT_URI, values) val outputStream = savedFile?.let { context.contentResolver.openOutputStream(it) } val fis = FileInputStream(file) var length : Int val buffer = ByteArray(8192) while (fis.read(buffer).also { length = it } > 0) outputStream?.write(buffer, 0, length) Toast.makeText(context, "Picture saved to $path", Toast.LENGTH_SHORT).show() println("Picture : $path / $savedFile") }catch (e : IOException){ Toast.makeText( context, "An error occured while saving the file", Toast.LENGTH_SHORT ).show() e.printStackTrace() }catch (e : Exception) { e.printStackTrace() } }else{ try { val dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).absolutePath + "/FolderName" val image = File(dir, file.name) val fis = FileInputStream(file) val fos = FileOutputStream(image) var length : Int val buffer = ByteArray(8192) while (fis.read(buffer).also { length = it } > 0) { fos.write(buffer, 0, length) } }catch (e : IOException){ Toast.makeText( context, "An Error occurred while saving the file", Toast.LENGTH_SHORT ).show() e.printStackTrace() }catch (e : Exception) { e.printStackTrace() } } } psst ~ All of these actions are performed without requesting any permissions.
When I'm trying to access images from contentResolver, it always returns 0.
private fun loadImages() : List { val photos = mutableListOf() val collection = sdk29andUp { MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY) } ?: MediaStore.Images.Media.EXTERNAL_CONTENT_URI val projection = arrayOf( MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.DATE_ADDED ) contentResolver.query( collection, projection, null, null, null )?.use { cursor -> val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID) val displayNameColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME) val dateAddedColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_ADDED) cursor.moveToFirst() while (cursor.moveToNext()) { val id = cursor.getLong(idColumn) val name = cursor.getString(displayNameColumn) val date = cursor.getLong(dateAddedColumn) val contentUri = ContentUris.withAppendedId( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id ) photos.add( Image( id = id, name = name, entryDate = date, contentUri = contentUri )) } } return photos.toList() } If someone can help me with this, I would really appreciate that.
Edit : The app crashes on API 28 and Before, so I'll have to request permissions for those API levels, but it means there is a solution for api's after 28
Источник: https://stackoverflow.com/questions/750 ... -by-my-app
I need a method to access the images stored in external storage by my app.
I want to access those images without requesting READ_EXTERNAL_STORAGE or READ_MEDIA_IMAGES from the user
I'm using ACTION_GET_CONTENT to get the image from the user.
val launcher = rememberLauncherForActivityResult(contract = ActivityResultContracts.StartActivityForResult()){ val uri : String = it.data?.data?.toString()?:"null" if (uri != "null"){ val mimeType = context.contentResolver.getType(uri.toUri()).toString() it.data?.data?.let { returnUri -> context.contentResolver.query(returnUri, null, null, null, null) }?.use { cursor -> val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE) cursor.moveToFirst() val name = cursor.getString(nameIndex) val size = cursor.getLong(sizeIndex) image = image.copy( path = uri, mimeType = mimeType.replace("image/",""), size = size, name = name, uri = it.data?.data ) } }else{ image = image.copy(path = uri) } } Calling the launcher for result
launcher.launch(Intent(Intent.ACTION_GET_CONTENT).setType("image/*")) After performing the required actions on the image, I save the image using the following method.
fun saveFile(context : Context, file: File) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){ try { val values = ContentValues() val path = Environment.DIRECTORY_PICTURES + "/FolderName" values.put(MediaStore.MediaColumns.DISPLAY_NAME, file.name) values.put(MediaStore.MediaColumns.MIME_TYPE, "image/*") values.put(MediaStore.MediaColumns.RELATIVE_PATH, path) val savedFile = context.contentResolver.insert(Media.EXTERNAL_CONTENT_URI, values) val outputStream = savedFile?.let { context.contentResolver.openOutputStream(it) } val fis = FileInputStream(file) var length : Int val buffer = ByteArray(8192) while (fis.read(buffer).also { length = it } > 0) outputStream?.write(buffer, 0, length) Toast.makeText(context, "Picture saved to $path", Toast.LENGTH_SHORT).show() println("Picture : $path / $savedFile") }catch (e : IOException){ Toast.makeText( context, "An error occured while saving the file", Toast.LENGTH_SHORT ).show() e.printStackTrace() }catch (e : Exception) { e.printStackTrace() } }else{ try { val dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).absolutePath + "/FolderName" val image = File(dir, file.name) val fis = FileInputStream(file) val fos = FileOutputStream(image) var length : Int val buffer = ByteArray(8192) while (fis.read(buffer).also { length = it } > 0) { fos.write(buffer, 0, length) } }catch (e : IOException){ Toast.makeText( context, "An Error occurred while saving the file", Toast.LENGTH_SHORT ).show() e.printStackTrace() }catch (e : Exception) { e.printStackTrace() } } } psst ~ All of these actions are performed without requesting any permissions.
When I'm trying to access images from contentResolver, it always returns 0.
private fun loadImages() : List { val photos = mutableListOf() val collection = sdk29andUp { MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY) } ?: MediaStore.Images.Media.EXTERNAL_CONTENT_URI val projection = arrayOf( MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.DATE_ADDED ) contentResolver.query( collection, projection, null, null, null )?.use { cursor -> val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID) val displayNameColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME) val dateAddedColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_ADDED) cursor.moveToFirst() while (cursor.moveToNext()) { val id = cursor.getLong(idColumn) val name = cursor.getString(displayNameColumn) val date = cursor.getLong(dateAddedColumn) val contentUri = ContentUris.withAppendedId( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id ) photos.add( Image( id = id, name = name, entryDate = date, contentUri = contentUri )) } } return photos.toList() } If someone can help me with this, I would really appreciate that.
Edit : The app crashes on API 28 and Before, so I'll have to request permissions for those API levels, but it means there is a solution for api's after 28
Источник: https://stackoverflow.com/questions/750 ... -by-my-app
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Ограничить несанкционированный доступ к изображениям профиля в CodeIgniter 4
Anonymous » » в форуме Php - 0 Ответы
- 17 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Ограничить несанкционированный доступ к изображениям профиля в CodeIgniter 4
Anonymous » » в форуме Php - 0 Ответы
- 5 Просмотры
-
Последнее сообщение Anonymous
-