Skip to content

Instantly share code, notes, and snippets.

@NoahZu
Created August 15, 2018 07:34
Show Gist options
  • Select an option

  • Save NoahZu/38ac3de8f1bebe8d0307ccccf0bd3180 to your computer and use it in GitHub Desktop.

Select an option

Save NoahZu/38ac3de8f1bebe8d0307ccccf0bd3180 to your computer and use it in GitHub Desktop.
采用未解码的方式去获取Bitmap
/**
* Author: jzu
* Date: 2018/8/15
* Function: Fresco操作图片的工具类
*/
object FrescoUtil {
/**
* scaleSize : 缩放倍数
*/
fun loadImage(uri: Uri,scaleSize : Int,callback: Callback) {
val request = ImageRequest.fromUri(uri)
val localCache = getCacheFile(uri.toString())
if (localCache == null) {
val options = BitmapFactory.Options()
options.inSampleSize = scaleSize
val bitmap = BitmapFactory.decodeFile(localCache.toString(),options)
callback.onSuccess(bitmap)
} else {
val pipeline = Fresco.getImagePipeline()
val dataSource = pipeline.fetchEncodedImage(request, true)
dataSource.subscribe(object : BaseDataSubscriber<CloseableReference<PooledByteBuffer>>() {
override fun onFailureImpl(dataSource: DataSource<CloseableReference<PooledByteBuffer>>?) {
callback.onFail()
}
override fun onNewResultImpl(dataSource: DataSource<CloseableReference<PooledByteBuffer>>?) {
if (dataSource == null){
return
}
if (!dataSource.isFinished) {
return
}
if (dataSource.result == null){
return
}
val inputStream = PooledByteBufferInputStream(dataSource.result!!.get());
try {
val options = BitmapFactory.Options()
options.inSampleSize = scaleSize
val bitmap = BitmapFactory.decodeStream(inputStream,null,options)
ThreadUtil.postOnUI(Runnable {
callback.onSuccess(bitmap)
})
} finally {
Closeables.closeQuietly(inputStream)
}
}
}, CallerThreadExecutor.getInstance())
}
}
/**
* 获取本地缓存文件,如果没有则返回空
*
* @param path
* @return
*/
fun getCacheFile(path: String): File? {
var cacheFile: File? = null
val mainFileCache = ImagePipelineFactory
.getInstance()
.mainFileCache
val simpleCacheKey = SimpleCacheKey(path)
if (mainFileCache.hasKey(simpleCacheKey)) {
val resource = mainFileCache.getResource(simpleCacheKey) as FileBinaryResource
if (resource != null) {
cacheFile = resource.file
}
}
return cacheFile
}
interface Callback{
fun onSuccess(bitmap : Bitmap)
fun onFail()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment