resizing animated GIF while keeping it's animation using java

后端 未结 3 1480
暗喜
暗喜 2020-12-30 14:00

i am using Graphics2D in java to resize images, it works perfect with jpg,png and other formats. my problem is the animated GIF images, after re-sizing the animation is gone

3条回答
  •  梦谈多话
    2020-12-30 14:44

    I found two sources which when combined can be used to resize the image while keeping the animation.

    On this question ( Convert each animated GIF frame to a separate BufferedImage ) look for the answer by Alex Orzechowski. His code takes a gif file and converts it to an array of ImageFrames (which is a class he made which wraps a BufferedImage). Then look at this code which converts a sequence of BufferedImages to a gif file ( http://elliot.kroo.net/software/java/GifSequenceWriter/ ).

    As you could probably guess, all you need to do is upload the gif, use Alex's code to convert it to an array of ImageFiles/BufferedImages, use your Graphics2D code to resize each frame (you'll need to add a setImage method to Alex's ImageFrame class), then use Elliot's code to convert the array to a gif! Here is what mine looks like:

    public static void main( String[] args )
    {
      try {
         File imageFile = new File( "InputFile" );
         FileInputStream fiStream = new FileInputStream( imageFile );
    
         ImageFrame[] frames = readGif( fiStream );
         for( int i = 0; i < frames.length; i++ ){
            //code to resize the image
            BufferedImage image = ImageUtilities.resizeImage( frames[ i ].getImage(), newWidth, newHeight);
            frames[ i ].setImage( image );
       }
    
         ImageOutputStream output =
           new FileImageOutputStream( new File( "OutputFile" ) );
    
         GifSequenceWriter writer =
           new GifSequenceWriter( output, frames[0].getImage().getType(), frames[0].getDelay(), true );
    
         writer.writeToSequence( frames[0].getImage() );
         for ( int i = 1; i < frames.length; i++ ) {
            BufferedImage nextImage = frames[i].getImage();
            writer.writeToSequence( nextImage );
         }
    
         writer.close();
         output.close();
      }
      catch ( FileNotFoundException e ) {
         System.out.println( "File not found" );
      }
      catch ( IOException e ) {
         System.out.println( "IO Exception" );
      }
    }
    

    This code, however, does not account for gif images with different amount of time elapsing between frames.

提交回复
热议问题