Kotlin:如何将图像从Internet保存到内部存储 [英] Kotlin: How to save image from Internet to internal storage

查看:193
本文介绍了Kotlin:如何将图像从Internet保存到内部存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android Studio的新手,尤其是Kotlin.我需要从互联网加载图像,然后将其保存到手机.我尝试使用Glide作为位图加载图像,然后将其保存.但这是行不通的.这段代码是我发现的最好的东西,但是没用.

I am new to Android Studio and especially to Kotlin. I need to load image from internet and then save it to phone. I tried to load image with Glide as Bitmap and then save it. But it doesn't work. This code is best thing i found but it doesn't work.

try {
var bitmap = Glide.with(this)
        .asBitmap()
        .load("https://s3.amazonaws.com/appsdeveloperblog/Micky.jpg")
        .apply(RequestOptions().override(100).downsample(DownsampleStrategy.CENTER_INSIDE).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE))
        .submit().get()
    val wrapper = ContextWrapper(applicationContext)
    var file = wrapper.getDir("Images", Context.MODE_PRIVATE)
    file = File(file, "img.jpg")
    val out = FileOutputStream(file)
    bitmap.compress(Bitmap.CompressFormat.JPEG, 85, out)
    out.flush()
    out.close()
}
catch (e: Exception) {
    println(e)
}

我对问题的理解是在Glide的".submit().get()"部分中.但是,如果我将其取走,则压缩将不起作用.

How I understood problem is in this ".submit().get()" part of Glide. But if I take it away then compress doesn't work.

推荐答案

submit():返回一个可以用来在后台线程上进行阻塞获取的Future.

submit(): Returns a future that can be used to do a blocking get on a background thread.

get():必要时等待计算完成,然后检索其结果.

get(): Waits if necessary for the computation to complete, and then retrieves its result.

如果要从url下载图像并将其保存到内部存储中,则应使用后台线程来执行此操作.如果您在主线程上调用,则您的应用可能会引发ANR对话框.

In your case to download an image from a url and save it to internal storage, you should use a background thread to do that. If you calling on main thread, your app might be throws ANR dialog.

在这里,我将演示如何使用AsyncTask API下载和保存图像

Here I will demo how to download and save the image by using AsyncTask API

首先编写一个类来下载和保存图像.

First write a class to download and save the image.

class DownloadAndSaveImageTask(context: Context) : AsyncTask<String, Unit, Unit>() {
    private var mContext: WeakReference<Context> = WeakReference(context)

    override fun doInBackground(vararg params: String?) {
        val url = params[0]
        val requestOptions = RequestOptions().override(100)
            .downsample(DownsampleStrategy.CENTER_INSIDE)
            .skipMemoryCache(true)
            .diskCacheStrategy(DiskCacheStrategy.NONE)

        mContext.get()?.let {
            val bitmap = Glide.with(it)
                .asBitmap()
                .load(url)
                .apply(requestOptions)
                .submit()
                .get()

            try {
                var file = it.getDir("Images", Context.MODE_PRIVATE)
                file = File(file, "img.jpg")
                val out = FileOutputStream(file)
                bitmap.compress(Bitmap.CompressFormat.JPEG, 85, out)
                out.flush()
                out.close()
                Log.i("Seiggailion", "Image saved.")
            } catch (e: Exception) {
                Log.i("Seiggailion", "Failed to save image.")
            }
        }
    }
}

然后参加活动

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        DownloadAndSaveImageTask(this).execute("https://s3.amazonaws.com/appsdeveloperblog/Micky.jpg")
    }
}

如果要保存到内部存储器

If you want to save to internal storage

var file = File(it.filesDir, "Images")
if (!file.exists()) {
    file.mkdir()
}
file = File(file, "img.jpg")

它将图像保存在路径data/data/yourapppackagename/files/Images/img.jpg

这篇关于Kotlin:如何将图像从Internet保存到内部存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆