Skip to content
Advertisement

How to download and save Bitmap of animated webp?

When I am using webp files for animated sticker packs it get rejected but if use same files for static stickers it get excepted. After looking all the codes I came to know that this is the last point where those files becomes problematic. But don not know how to identify if webp files stays as animated webp after saving. Please share your thought.

ps: I am using these webp files for whatsapp sticker packs. there is flag “animated_sticker_pack”. we have to tell whatsapp that this pack contains only animated webp with proper fomrat. If I set it false then sticker pack get added (let it be static or animated webp). But if I set that flag true then those animated webp get rejected for pack showing error that There’s problem with this pack…. So it might be that frames are lesser then it required. It get accepted as static means it might have single frame only. To avoid issues regarding file type,format,size and all I am using the sample files from WhatsApp sample app

Code:

public static void SaveImage(Bitmap finalBitmap, String name, String identifier) {

        String root = path + "/" + identifier;
        File myDir = new File(root);
        myDir.mkdirs();

        String fname = name;
        File file = new File(myDir, fname);
        
        if (file.exists()){
            file.delete();
        }
        
        try {

            // FileOutputStream 
            FileOutputStream out = new FileOutputStream(file);

            // Bitmap.compress
            finalBitmap.compress(Bitmap.CompressFormat.WEBP, 100, out); 
            
            // close
            out.flush();
            out.close();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
 }

////////////////////Other methods before saving images

private Bitmap downloadImageBitmap(String sUrl, String sIdentifier, String sName) {
    imageFileName = getLastBitFromUrl(sUrl).replace(".png", ".webp");
    identifier = sIdentifier;
    name = sName;
    Bitmap bitmap = null;
    try {
        InputStream inputStream = new URL(sUrl).openStream(); // Download Image from URL
        bitmap = BitmapFactory.decodeStream(inputStream); // Decode Bitmap
        inputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
     return bitmap;
}

@Override
protected Bitmap doInBackground(String... params) {
    return downloadImageBitmap(params[0], params[1], params[2]);
}

protected void onPostExecute(Bitmap result) {
    SaveImage(result, imageFileName, identifier);
}

Answer

You can download and save in doInBackground()

    InputStream inputStream = new URL(sUrl).openStream(); // Download Image from URL

    FileOutputStream out = new FileOutputStream(file);

Then make a loop where you read bytes in a buffer from input stream and write to output stream.

Don’t forget to close all streams when done.

Advertisement