Why Images.Media.insertImage return null

前端 未结 7 513
耶瑟儿~
耶瑟儿~ 2020-12-03 20:55

I have some code where I run the method MediaStore.Images.Media.insertImage (inserting it from a source not a file name), This code saves the image to the MediaStore and ret

7条回答
  •  Happy的楠姐
    2020-12-03 21:42

    I faced the same issue and nothing worked. But finally after 3 hours it worked.

    Solution: I found that It works fine until we delete that image from our image gallery. After that It starts returning null. But suddenly I tried changing title and description name and it worked like a charm.

    So I've added a date with the title and description of bitmap. In case, user deletes bitmap manually from file manager. Still It works.

      private fun insertImage(cr: ContentResolver,
            source: Bitmap?,
            title: String,
            description: String
        ): String? {
    
            val sdf = SimpleDateFormat("MM-dd-yyyy-hh.mm.ss.SSS.a", Locale.US)
            val date=sdf.format(Date())
    
            val values = ContentValues()
            values.put(Images.Media.TITLE, title)
            values.put(Images.Media.DISPLAY_NAME, title+date)
            values.put(Images.Media.DESCRIPTION, description+date)
            values.put(Images.Media.MIME_TYPE, "image/jpeg")
            // Add the date meta data to ensure the image is added at the front of the gallery
            values.put(Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000)
            values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis())
    
            var url: Uri? = null
            var stringUrl: String? = null    /* value to be returned */
    
            try {
                url = cr.insert(Images.Media.EXTERNAL_CONTENT_URI, values)
    
                if (source != null) {
                    val imageOut = cr.openOutputStream(url!!)
                    try {
                        source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut)
                    } finally {
                        imageOut!!.close()
                    }
    
    
                } else {
                    cr.delete(url!!, null, null)
                    url = null
                }
            } catch (e: Exception) {
                if (url != null) {
                    cr.delete(url, null, null)
                    url = null
                }
            }
    
            if (url != null) {
                stringUrl = url.toString()
            }
    
            return stringUrl
        }
    

    I Implemented to share news bitmap in this app and it's working fine. Enjoy!

提交回复
热议问题