Android开发,kotlin协程保存图片

1.添加依赖

在build.gradle(Module:app)文件添加以下依赖

implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.2.0'

2.将要处理的事件放到协程中,定义一个函数

//协程处理保存图片
private suspend fun savePhoto() { //关键字suspend:在另外的线程允许挂起
    withContext(Dispatchers.IO) {
        //定义线程的范围
        //获取图像的位图资源
        val holder: PagerPhotoViewHolder = (viewPager2[0] as RecyclerView).findViewHolderForAdapterPosition(viewPager2.currentItem) as PagerPhotoViewHolder
        val bitmap: Bitmap = holder.itemView.pagerPhoto.drawable.toBitmap() //可以传入图片的大小,默认是显示的图片

        //设置保存地址
        val saveUri: Uri = requireContext().contentResolver.insert(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            ContentValues()
        ) ?: kotlin.run {
            Toast.makeText(requireContext(), "存储失败", Toast.LENGTH_SHORT).show()
            return@withContext
        }

        //保存图片
        requireContext().contentResolver.openOutputStream(saveUri).use {
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, it)) { //90%的压缩率,it是输出流
                //在主线程提示用户
                MainScope().launch { Toast.makeText(requireContext(), "存储成功", Toast.LENGTH_SHORT).show() }
            } else {
                MainScope().launch { Toast.makeText(requireContext(), "存储失败", Toast.LENGTH_SHORT).show() }
            }
        }
    }
}

3.调用协程

saveButton.setOnClickListener {
    viewLifecycleOwner.lifecycleScope.launch {
        //lifecycleScope使协程的生命周期随着activity的生命周期变化
        savePhoto()
    }
}
发布了77 篇原创文章 · 获赞 40 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/y_dd6011/article/details/104171798