常見的獲取圖片格式的方式
Android中常見的圖片格式有png、jpeg(jpg)、gif、webp,不同格式的圖片,那麼如何獲取圖片類型呢?
常見的有兩種方式,一種是在Bitmap加載過程中,通過BitmapFactory.Options#outMimeType來獲取圖片對應的格式,另一種是通過文件頭信息來判斷。
效果圖:
具體實現
因爲我們這裏針對的是網絡圖片,所以第一步是將圖片下載到本地。
通過[BitmapFactory.Options#outMimeType]獲取圖片格式
接着我們可以通過BitmapFactory.decodeFile(String pathName, Options opts)
方法,從opts中獲取對應的outMimeType,然後根據outMimeType即可判斷對應的類型了。
具體代碼如下:
Observable.create<File> {
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<String> {
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<File> {
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<String> {
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。
項目地址
具體頁面地址: BitmapTypeActivity.kt
參考
https://my.oschina.net/ososchina/blog/1610685?nocache=1591319567444