android - 如何使用 Picasso 将 imageView 中包含的图像保存到内部存储
问题描述
好的,我在一个片段中运行
我有一个使用 picasso 随机获取其图像的 imageView,我希望您能帮助我使用按钮将该图像保存到设备的内部存储中
我生成随机图像的代码:
private fun imageRandomFun() {
val quest1 = "https://proxxcraft.com/"
Picasso.get().load(quest1).memoryPolicy(MemoryPolicy.NO_CACHE).into(memeRandomView)
Picasso.get().isLoggingEnabled = true
}
我的布局:
<ImageView
android:id="@+id/memeRandomView"
android:layout_width="385dp"
android:layout_height="452dp"
android:layout_marginStart="32dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="32dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.578"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView8" />
<Button
android:id="@+id/nextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="40dp"
android:clickable="true"
android:text="Next"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/memeRandomView" />
<TextView
android:id="@+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="32dp"
android:text="Memes Random"
android:textColor="#393636"
android:textSize="20dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/downloadButton"
style="@style/Widget.MaterialComponents.ExtendedFloatingActionButton.Icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:text="Descargar"
app:icon="@drawable/download"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/memeRandomView" />
解决方案
试试下面的,由于图像保存代码太长,你可以使用这个库来让你更轻松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
您可以将其作为文件保存到设备存储中的方法
推荐阅读
- python - 非结构化点云的区域增长:验证 pcl 失败
- ios - 如何使用具有自动布局的 init(frame:) 实例化自定义 UIView 子类?
- sql - 这个 sql 连接语法有什么问题
- transactions - 关闭事务 CICS
- python-2.7 - 导入 mxnet 时出现非法指令(核心转储)
- css - 如何解决导航滚动问题?
- file - 如何正确复制二进制文件
- java - Spring Boot 应用程序正在使用 Docker 容器的 Redhat Enterprise Linux 服务器上运行,并且希望在 Windows 上访问该应用程序
- javascript - Websocket 服务器:TypeError ws.send() 不是函数
- java - 选择文本时如何停止 EditText 显示键盘?