Search code examples
androidgifconverterswebp

Android convert gif to animated webp


I tried many things to convert a gif file to a animated webp file, but it doesn't work.

I firstly created a gif out of a webp/png file and loaded it into a file to save it as webp:

        //Bitmap from  png / webp
        Bitmap bmpAnimGif = BitmapFactory.decodeFile(String.valueOf(file));

        //Converting it into gif
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        AnimatedGifEncoder encoder = new AnimatedGifEncoder();
        encoder.start(bos);
        encoder.addFrame(bmpAnimGif);
        encoder.finish();
        byte[] array = bos.toByteArray();

        // Save to file (gif)
        File output = new File(StickerPackActivity.BASE_PATH  + "/" + "temp_animated.gif");
        FileOutputStream fos = new FileOutputStream(output);
        fos.write(array);
        fos.close();

        //load gif and saved it as webp

        File output2 = new File(StickerPackActivity.BASE_PATH  + "/" + "temp_animatedwebp.webp");
        fOut = new FileOutputStream(output2);
        compressImage(BitmapFactory.decodeFile(String.valueOf(output)), false).compress(Bitmap.CompressFormat.WEBP_LOSSY, 80, fOut);
        fOut.flush();
        fOut.close();

I guess the last step is wrong... Would be nice if you could help me with my problem.


Solution

  • I was able to convert gif to animated webp using:

       implementation 'com.arthenica:ffmpeg-kit-full:4.4.LTS'
    

    FFmpegSession session = FFmpegKit.execute("-i input_path/input.gif -vcodec webp -loop 0 -pix_fmt yuv420p output_path/output.webp");
    
        
        if (ReturnCode.isSuccess(session.getReturnCode())) {
    
            tvFilePath.setText("success");
            // SUCCESS
    
        } else if (ReturnCode.isCancel(session.getReturnCode())) {
    
            // CANCEL
    
        } else {
    
            // FAILURE
            Log.d("ffmpeg", String.format("Command failed with state %s and rc %s.%s", session.getState(), session.getReturnCode(), session.getFailStackTrace()));
    
        }