美文网首页
Android开发网络图片下载转为Bitmap

Android开发网络图片下载转为Bitmap

作者: 你的益达233 | 来源:发表于2020-12-18 09:30 被阅读0次

思路:因为不能在主线程做网络操作,所以用了下RxJava进行线程切换

复制就能用的代码如下:

Observable.just("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1606300439769&di=a45ce46a5abdde1e6de25245ddd57b31&imgtype=0&src=http%3A%2F%2Fi0.hdslb.com%2Fbfs%2Farticle%2F9ee63d88f25139c536ee41492c41de23b380c026.jpg")
                    .map(object : Function<String, Bitmap> {
                        override fun apply(t: String): Bitmap {
                            val url: URL
                            var connection: HttpURLConnection? = null
                            var bitmap: Bitmap? = null
                            try {
                                url = URL(t)
                                connection = url.openConnection() as HttpURLConnection
                                connection!!.connectTimeout = 6000 //超时设置
                                connection!!.doInput = true
                                connection!!.useCaches = false //设置不使用缓存
                                val inputStream = connection!!.inputStream
                                bitmap = BitmapFactory.decodeStream(inputStream)
                                inputStream.close()
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                            return bitmap!!
                        }

                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object :Consumer<Bitmap>{
                        override fun accept(t: Bitmap?) {
                            
                                

                        }

                    })

相关文章

网友评论

      本文标题:Android开发网络图片下载转为Bitmap

      本文链接:https://www.haomeiwen.com/subject/drkxnktx.html