您的位置:首页 > 理论基础 > 计算机网络

分享Fresco缓存中的图片

2016-05-21 15:50 483 查看
由于使用Fresco框架加载网络图片,然后又面临要分享图片的需求,于是研究了下如何使用分享fresco缓存下的图片。

已经确定缓存中有的图片:

先说思路,本来是想直接分享缓存路径中的图片缓存的,但是Fresco缓存的格式是.cnt,不能直接分享,于是通过fresco本身自带的功能获取到图片的bitmap,在将bitmap存到SD卡上,再按照sd卡上的路径进行分享。

具体实现如下:

//从缓存中获取图片的bitmap
ImageRequest imageRequest=ImageRequestBuilder.newBuilderWithSource(Uri.parse(url))
.setResizeOptions(resizeOptions)
.setAutoRotateEnabled(true)
.build();
ImagePipeline imagePipeline = Fresco.getImagePipeline();
DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, this);
CloseableReference<CloseableImage> imageCloseableReference =  dataSource.getResult();
final String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/share"+"/"+photoFiles.get(position).getName();
if (imageCloseableReference != null) {
final CloseableImage image = imageCloseableReference.get();
if (image != null && image instanceof CloseableStaticBitmap) {
CloseableStaticBitmap closeableStaticBitmap = (CloseableStaticBitmap) image;
Bitmap bitmap = closeableStaticBitmap.getUnderlyingBitmap();
if (bitmap != null) {

//把获取的Bitmap转存到SD卡上
File docment = new File(sdPath);
try {
FileOutputStream fos = new FileOutputStream(docment);
bitmap.compress(Bitmap.CompressFormat.JPEG,90,fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
File f = new File(sdPath);
Uri imagePath = Uri.fromFile(f);
//把SD卡路径上的图片分享出去
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, imagePath);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "分享到"));
mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, imagePath));
}
}
}


这样就可以在Fresco的基础上分享图片了。

如果你不确定你的缓存中是否存在这张图片,那么可以使用下面的代码,在图片获取到了之后在进行分享

DraweeController controller = Fresco.newDraweeControllerBuilder()
.setControllerListener(new BaseControllerListener<ImageInfo>(){
@Override
public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
super.onFinalImageSet(id, imageInfo, animatable);
//1:获取bitmap
//2:存sd卡
//3:分享sd的图片
}
})
.build();
frescoView.setController(controller);


当然这只是自己摸索出来的方式,确实比较繁琐,如果你知道更好的方式,希望可以指点,交流下!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息