0

How can download an image to storage in Jetpack Compose

I'm experimenting with Compose and trying to make a photo download to storage, but i dont know how. I tried to do it through contentResolver but it gives me an error

NikAn
  • 1
  • Downloading an image is a network operation. It does not differ with the UI layer used - Compose or View system. – Abhimanyu May 25 '23 at 06:02

1 Answers1

0

I have recently worked on a project where I Need to download an image from a URL which I have accomplished using the below code.

You have to create a ViewModel Put these two functions and call them from the Compose Screen You will be able to download the image.

Add dependency in build.gradle(app-level)

implementation("io.coil-kt:coil-compose:2.2.2")

My ViewModel As A Reference

@HiltViewModel
class ImageViewModel @Inject constructor(
        private val application: Application,
) : ViewModel() {
    
    
     
        private fun persistImage(context: Context, file: File, bitmap: Bitmap) {
            val os: OutputStream
            try {
                os = FileOutputStream(file)
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os)
                os.flush()
                os.close()
    
                MediaScannerConnection.scanFile(
                    context, arrayOf(file.toString()),
                    null, null
                )
    
                state = state.copy(isDownloading = false)
                state = state.copy(imageSaved = true)
                _showDownloadToast.value = true
            } catch (e: Exception) {
                Log.e(javaClass.simpleName, "Error writing bitmap", e)
            }
        }
    
       
        private fun downloadImageFromUrl1(context: Context, url: String) {
            viewModelScope.launch(Dispatchers.IO) {
    
                val loader = ImageLoader(context)
                val request = ImageRequest.Builder(context)
                    .data(url)
                    .allowHardware(false) // Disable hardware bitmaps.
                    .build()
    
                val result = (loader.execute(request) as SuccessResult).drawable
    
                val bitmap = (result as BitmapDrawable).bitmap
    
                val path =
                    File(application.filesDir.toString() + "/Folder")
    
                if (!path.exists())
                    path.mkdirs()
    
    
                val imageFile = File(path, "${FilenameUtils.getName(url)}.jpg")
                if (imageFile.exists()) {
                   //File Name Already Exist Do Whatever
                } else {
                    persistImage(context, imageFile, bitmap)
    
                }
            }
        }
    
     
    }
Chirag Thummar
  • 665
  • 6
  • 16