How to save image to sdcard when using Fresco?

4.3k views Asked by At

I am using Fresco to download and display Gifs in my app. I want to save the image to sdcard when click it, but i can't figure out how to do it.

final View view = inflater.inflate(R.layout.fragment_gif_viewer, container, false);
SimpleDraweeView draweeView = (SimpleDraweeView) view.findViewById(R.id.image);
Uri uri = Uri.parse(imageUrl);
DraweeController controller = Fresco.newDraweeControllerBuilder()
        .setUri(uri)
        .setAutoPlayAnimations(true)
        .build();
draweeView.setController(controller);

draweeView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Save the gif to /sdcard/test.gif
    }
});

I try to get the bitmap from the SimpleDraweeView following the instruction of How do I save an ImageView as an image?, but it's getDrawingCache() returns null

2

There are 2 answers

3
s1rius On

You can do like this

ImageRequest downloadRequest = ImageRequest.fromUri(uri);
CacheKey cacheKey = DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(downloadRequest);
if (ImagePipelineFactory.getInstance().getMainDiskStorageCache().hasKey(cacheKey)) {
    BinaryResource resource = ImagePipelineFactory.getInstance().getMainDiskStorageCache().getResource(cacheKey);
    File cacheFile = ((FileBinaryResource) resource).getFile();
    FileInputStream fis = new FileInputStream(cacheFile);
    ImageFormat imageFormat = ImageFormatChecker.getImageFormat(fis);
    switch (imageFormat) {
        case GIF:
        //copy cacheFile to sdcard
        break;
    }
}
2
tyronen On

You can use the image pipeline directly to extract your GIF from disk cache.

Then you can use Java File methods to write it to the file system.