如何使用 Picasso 将 imageView 中包含的图像保存到内部存储器

时间:2021-03-02 21:10:36

标签: android kotlin

好的,我在一个片段中运行

我有一个 imageView 可以用 picasso 随机获取它的图像,我希望你能帮助我使用按钮将该图像保存到设备的内部存储中

我生成随机图像的代码:

@Setting

我的布局:


private fun imageRandomFun() {
        val quest1 = "https://proxxcraft.com/"
        Picasso.get().load(quest1).memoryPolicy(MemoryPolicy.NO_CACHE).into(memeRandomView)
        Picasso.get().isLoggingEnabled = true
    }

1 个答案:

答案 0 :(得分:0)

尝试以下操作,由于图像保存代码太长,您可以使用此库让您更轻松implementation 'com.blankj:utilcodex:1.30.0'

确保已授予存储权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

private fun downloadImage(){
    val quest1 = "https://proxxcraft.com/"
    Picasso.get().load(quest1).into(object : Target {
        override fun onBitmapLoaded(bitmap: Bitmap, from: LoadedFrom) {
            val file = ImageUtils.save2Album(bitmap, Bitmap.CompressFormat.JPEG, 100)
            if (file!!.exists()) ToastUtils.showShort("Image Saved!")
        }
        override fun onBitmapFailed(e: Exception, errorDrawable: Drawable) {}
        override fun onPrepareLoad(placeHolderDrawable: Drawable) {}
    })
}

加载图像时,onBitmapLoaded 方法返回一个 Bitmap,您可以将其作为文件保存到设备存储中