微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

调整动画GIF的大小,同时使用java保持动画

我在java中使用Graphics2D来调整图像大小,它与jpg,png和其他格式完美配合.
我的问题是动画gif图像,重新调整动画后不见了!

这是我使用的方法

private BufferedImage doResize(int newWidth,int newHeight,double scaleX,double scaleY,BufferedImage source) {

    GraphicsConfiguration gc = getDefaultConfiguration();
    BufferedImage result = gc.createCompatibleImage(newWidth,newHeight,source.getColorModel().getTransparency());
    Graphics2D g2d = null;

    try {
        g2d = result.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.scale(scaleX,scaleY);
        g2d.drawImage(source,null);
    } finally {
        if (g2d != null) {
            g2d.dispose();
        }
    }

    return result;
}

所以,任何线索如何在重新调整尺寸后如何保持动画GIF?
谢谢.

解决方法

我找到了两个源,它们在组合时可用于在保持动画的同时调整图像大小.

在这个问题上(
Convert each animated GIF frame to a separate BufferedImage)寻找Alex Orzechowski的答案.他的代码接受一个gif文件并将其转换为ImageFrames数组(这是他创建的包装BufferedImage的类).然后看看这个将BufferedImages序列转换为gif文件代码
(http://elliot.kroo.net/software/java/GifSequenceWriter/).

你可能猜到,你需要做的就是上传gif,使用Alex的代码将其转换为ImageFiles / BufferedImages数组,使用你的Graphics2D代码调整每个帧的大小(你需要为Alex’s添加一个setimage方法) ImageFrame类),然后使用Elliot的代码将数组转换为gif!这是我的样子:

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" );
  }
}

然而,该代码不考虑具有在帧之间流逝的不同时间量的gif图像.

原文地址:https://www.jb51.cc/html/231854.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐