Android获取Bitmap网络图片类型

常见的获取图片格式的方式

Android中常见的图片格式有png、jpeg(jpg)、gif、webp,不同格式的图片,那么如何获取图片类型呢?

常见的有两种方式,一种是在Bitmap加载过程中,通过BitmapFactory.Options#outMimeType来获取图片对应的格式,另一种是通过文件头信息来判断。

效果图:

jpeg
png
gif
webp

具体实现

因为我们这里针对的是网络图片,所以第一步是将图片下载到本地。

通过[BitmapFactory.Options#outMimeType]获取图片格式

接着我们可以通过BitmapFactory.decodeFile(String pathName, Options opts)方法,从opts中获取对应的outMimeType,然后根据outMimeType即可判断对应的类型了。

具体代码如下:

Observable.create {
    val fileTask = Glide.with(this)
        .asFile()
        .load(jpgUrl)
        .submit()
    val file = fileTask.get()
    it.onNext(file)
    it.onComplete()
}
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .map {
        ivJpeg.setImageBitmap(BitmapFactory.decodeFile(it.absolutePath))
        it
    }
    .observeOn(Schedulers.io())
    .map({
        getBmpTypeByOptions(it.absolutePath)
    })
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(object : Observer {
        override fun onComplete() {
            LogUtils.e(TAG, "onComplete")
        }

        override fun onSubscribe(d: Disposable?) {
            LogUtils.e(TAG, "onSubscribe")
        }

        override fun onNext(t: String?) {
            LogUtils.e(TAG, "onNext")
            LogUtils.e(TAG, "onNext mimeType:" + t)
            tvJpegInfoByBmpOptions.text = tvJpegInfoByBmpOptions.text.toString() + t
        }

        override fun onError(e: Throwable?) {
            LogUtils.e(TAG, "onError")
        }

    })

核心代码:

fun getBmpTypeByOptions(filePath: String): String {
    val options = BitmapFactory.Options()
    options.inJustDecodeBounds = true
    BitmapFactory.decodeFile(filePath, options)
    return options.outMimeType
}
通过文件头信息来判断图片格式
Observable.create {
    var fileTask = Glide.with(this)
        .asFile()
        .load(gifUrl)
        .submit()
    val file = fileTask.get()
    it.onNext(file)
    it.onComplete()
}
    .subscribeOn(Schedulers.io())
    .observeOn(Schedulers.io())
    .map({
        FileTypeUtil.getMimeType(it.absolutePath)
    })
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(object : Observer {
        override fun onComplete() {
            LogUtils.e(TAG, "onComplete")
        }

        override fun onSubscribe(d: Disposable?) {
            LogUtils.e(TAG, "onSubscribe")
        }

        override fun onNext(t: String?) {
            LogUtils.e(TAG, "onNext")
            LogUtils.e(TAG, "onNext mimeType:" + t)
            tvGifInfoByHead.text = tvGifInfoByHead.text.toString() + t
        }

        override fun onError(e: Throwable?) {
            LogUtils.e(TAG, "onError")
        }

    })

核心代码在FileTypeUtil中,具体请看FileTypeUtil.java。

项目地址

tinyvampirepudge/AndroidStudy

具体页面地址: BitmapTypeActivity.kt

参考

https://my.oschina.net/ososchina/blog/1610685?nocache=1591319567444

你可能感兴趣的:(Android获取Bitmap网络图片类型)