Java ImageWriter BufferedImage 转 GIF [英] Java ImageWriter BufferedImage to GIF

查看:130
本文介绍了Java ImageWriter BufferedImage 转 GIF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望你们能帮我解决这个问题.我不确定这是 Java 中的错误还是我做错了什么,但我会选择后者.

I hope you guys can help me with this one. I'm not sure if it is a bug in Java or if I'm doing something wrong, but I'll go with the latter.

我想将 BufferedImage 转换为 GIF 图像.然后我希望以字节数组的形式将 GIF 保存在内存中.(我不想将文件保存到磁盘)

I want to turn a BufferedImage into a GIF image. I then wish to keep the GIF in the memory in the form of a byte array. (I do not want to save the file to disk)

程序应该捕获一个屏幕片段(只是为了创建一个快速图像)并使用 ImageIO ImageWriter 和 ByteArrayOutputStream 将其转换为 GIF 字节数组.

The program should capture a screen segment (just to create a quick image) and turn it into a GIF byte array using ImageIO ImageWriter and ByteArrayOutputStream.

下面的代码将向您展示该错误.程序将崩溃并给出 ArrayIndexOutOfBoundsException 并且数组保持为空.如果你用png"替换gif"它会工作得很好,因此我很困惑.还!如果我将图像保存到磁盘上的文件

The code below will show you the bug. The program will crash and give an ArrayIndexOutOfBoundsException and the array remains empty. If you replace the "gif" with "png" it will work just fine, hence my confusion. Also! If I save the image to a file on disk with

write.setOutput(ImageIO.createImageOutputStream(new FileOutputStream(new File("C:/Image.gif")));

它会正确地将其保存为 .gif 文件.

it will save it to a .gif file correctly.

所以我的问题是,我在这段代码中做错了什么?任何帮助将不胜感激!:)

So my question is, what did I do wrong in this patch of code? Any help will be greatly appreciated! :)

注意:这不是动画 GIF,也不涉及透明度.

Note: This is not an animated GIF, no transparency involved either.

    String format = "gif";
    Robot r = null;
    try {
        r = new Robot();
    } catch (AWTException e1) {
        e1.printStackTrace();
    }
    BufferedImage screen = r.createScreenCapture(new Rectangle(512,512));
    final BufferedImage gif = new BufferedImage(512,512,BufferedImage.TYPE_BYTE_INDEXED);
    Graphics2D g = gif.createGraphics();
    g.drawImage(screen,0,0,null);
    g.dispose();
    ImageWriter write = ImageIO.getImageWritersBySuffix(format).next();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        write.setOutput(ImageIO.createImageOutputStream(out));
        write.write(gif);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    for(int i=0; i < 10; i++) {
        System.out.println(out.toByteArray()[i]);
    }

推荐答案

com.sun.imageio.plugins.gif.* 中的流缓冲实现似乎有些奇怪(如果不是明显有问题的话)代码>.如果您没有明确刷新或关闭 ImageOutputStream,则内容不会被刷新,即使在关闭基础流之后.改变

 write.setOutput(ImageIO.createImageOutputStream(out));
 write.write(gif);

   ImageOutputStream imageos = ImageIO.createImageOutputStream(out);
   write.setOutput(imageos);
   write.write(gif);
   imageos.close();  // or imageos.flush();

这篇关于Java ImageWriter BufferedImage 转 GIF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆