Share Image Intent [The file format is not supported]

Viewed 24

I implemented share image to other apps using intent, I followed the recommended approach by saving the image first then getting its LocalBitmapUri. but when i run the app and share image i get the Toast message [The file format is not supported]. and i cant seem to figure out what I did wrong.. thanks.

fun shareItem(url: String?,context: Context,scope: CoroutineScope) {
    scope.launch {
        withContext(Dispatchers.IO){
            val i = Intent(Intent.ACTION_SEND)
            i.type = "image/*"
            i.putExtra(Intent.EXTRA_STREAM,
                getBitmap("d",context,"https://cdn2.thecatapi.com/images/3o8.jpg")?.let {
                    getLocalBitmapUri(
                        it,
                        context
                    )
                })
            startActivity(context,Intent.createChooser( i, "Share Image"),null)
        }
    }
}


fun getLocalBitmapUri(bmp: Bitmap,context: Context): Uri? {
    val builder = VmPolicy.Builder()
    StrictMode.setVmPolicy(builder.build())

    var bmpUri: Uri? = null
    try {
        val file = File(
            context.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
            "share_image_jj" + System.currentTimeMillis() + ".png"
        )
        val out = FileOutputStream(file)
        bmp.compress(Bitmap.CompressFormat.PNG, 90, out)
        out.close()
        bmpUri = Uri.fromFile(file)
    } catch (e: IOException) {
        e.printStackTrace()
    }
    return bmpUri
}


private suspend fun getBitmap(tag: String, context: Context, imageUrl: String): Bitmap? {
    var bitmap: Bitmap? = null

    val imageRequest = ImageRequest.Builder(context)
        .data(imageUrl)
        .target(
            ...//,
            onSuccess = { result ->
                Log.e(tag, "Coil loader success.")
                bitmap = result.toBitmap()
            }
        )
        .build()
    context.imageLoader.execute(imageRequest)

    return bitmap
}
0 Answers
Related