You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Glide将图片滑块中的图片保存至内部存储?(SimpleTarget已弃用)

没问题!既然你提到SimpleTarget<Bitmap>已经被弃用,那咱们就用Glide现在推荐的CustomTarget来实现这个需求,整体思路还是先获取Bitmap再保存到内部存储,下面是具体的实现步骤和代码示例:

具体实现

1. 通过Glide获取Bitmap(用CustomTarget替代SimpleTarget)

在按钮的点击事件里,我们可以用Glide的asBitmap()指定加载为Bitmap,然后通过CustomTarget来接收加载完成的Bitmap:

// 替换成你的Activity/Fragment上下文,以及对应的按钮和ImageView实例
saveBtn.setOnClickListener {
    Glide.with(this)
        .asBitmap()
        .load("你的图片源(URL/本地路径/资源ID等)") // 这里填你之前加载到ImageView的图片源
        .into(object : CustomTarget<Bitmap>() {
            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                // 拿到Bitmap后调用保存方法
                val saveSuccess = saveBitmapToInternalStorage(resource, "my_saved_image.jpg")
                if (saveSuccess) {
                    Toast.makeText(this@YourActivity, "图片已保存到内部存储", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this@YourActivity, "保存失败,请重试", Toast.LENGTH_SHORT).show()
                }
                // 手动回收Bitmap,避免内存占用
                resource.recycle()
            }

            override fun onLoadCleared(placeholder: Drawable?) {
                // 这里可以处理占位图的清理逻辑,比如清空ImageView的占位图
            }
        })
}

2. 实现Bitmap保存到内部存储的方法

内部存储不需要额外申请权限(因为只有你的应用能访问这些文件),我们可以用openFileOutput()来写入文件:

private fun saveBitmapToInternalStorage(bitmap: Bitmap, fileName: String): Boolean {
    return try {
        // 打开内部存储的输出流,MODE_PRIVATE表示仅本应用可访问
        openFileOutput(fileName, Context.MODE_PRIVATE).use { outputStream ->
            // 将Bitmap压缩为JPEG格式(也可以用PNG,根据需求选),质量设为80
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outputStream)
        }
        true
    } catch (e: IOException) {
        e.printStackTrace()
        false
    }
}

额外说明

  • 你可以通过filesDir获取内部存储的文件路径,比如filesDir.absolutePath + "/" + fileName,就能知道保存的文件具体位置
  • 如果之后需要加载这个保存的图片,直接用Glide加载对应的文件即可:
    val savedFile = File(filesDir, "my_saved_image.jpg")
    Glide.with(this).load(savedFile).into(imageView)
    
  • 注意Bitmap的内存管理:因为我们手动获取了Bitmap实例,所以在使用完后调用recycle()可以及时释放内存,避免内存泄漏

内容的提问来源于stack exchange,提问作者Dev Eloper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:29:41