Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Convert URL to File

I have a URL like this:

String url = "https://fbcdn-sphotos-d-a.akamaihd.net/hphotos-ak-ash4/t1/226654_10200335941702035_1975023945_n.jpg"

I want to convert this url to the file and I tried this:

fileName = new URL(url);

sourceFile = new File(fileName.getFile());

also i tried:

sourceFile = new File(fileName.getPath());

but both did not work for me. What should be done?

like image 404
Robz Avatar asked Nov 18 '25 08:11

Robz


1 Answers

  1. You can use glide library to get bitmap of url:
Glide.with(activity).load(imagePath).asBitmap().into(object :SimpleTarget<Bitmap>(){
                override fun onResourceReady(resource: Bitmap?, glideAnimation: GlideAnimation<in Bitmap>?) {


                     val file= GetFileFromBitmap().getFileFromBitmap(resource!!,activity)!!)


                }

            })
  1. To convert bitmap to file:
class GetFileFromBitmap
{
    fun getFileFromBitmap(bitmap: Bitmap,context: Context) : File?
    {
        val cache = context.externalCacheDir
        val shareFile = File(cache, "myFile.jpg")
        Log.d("share file type is", shareFile.absolutePath)
        try {
            val out = FileOutputStream(shareFile)
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
            out.flush()
            out.close()
            return shareFile
        } catch (e: Exception) {

        }
        return null
    }
}

Note: My code is in kotlin let me know if you face any issue.

like image 92
Suraj Vaishnav Avatar answered Nov 20 '25 21:11

Suraj Vaishnav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!