如何使用im4java调整缓冲图像的大小并将输出作为bufferedImage?

时间:2015-09-23 12:30:56

标签: java image resize im4java

当我尝试调整图像大小时,我得到一个异常,说“java.lang.IllegalStateException:给定格式没有ImageReader”。

 public static void main(String... args) throws Exception {   
        IMOperation op = new IMOperation();
        op.addImage();                       
        op.resize(350)
        op.addImage()               
        BufferedImage images = ImageIO.read(new File("image.jpg")); 

        // set up command
        ConvertCmd convert = new ConvertCmd();
        Stream2BufferedImage s2b = new Stream2BufferedImage();
        convert.setOutputConsumer(s2b);

        // run command and extract BufferedImage from OutputConsumer
        convert.run(op,images);
        BufferedImage img = s2b.getImage();
    }

2 个答案:

答案 0 :(得分:2)

BufferedImage images = ImageIO.read(new File("image.jpg")); 
    int type = (images.getTransparency() == Transparency.OPAQUE)
            ? BufferedImage.TYPE_INT_RGB
            : Buffenter code hereeredImage.TYPE_INT_ARGB;
    BufferedImage finalImage = images;
    int w = 40;
    int h = 40;
    BufferedImage resizedImage = new BufferedImage(w, h, type);
    Graphics2D g2 = resizedImage.createGraphics();
    g2.drawImage(finalImage, 0, 0, null);
    g2.dispose();
    finalImage = resizedImage;

这会将bufferedImage的大小调整为给定尺寸并返回新的bufferedImage

答案 1 :(得分:2)

雅人我已经解决了这个问题。实际上我必须指定输出图像的图像类型

public static void main(String... args) throws Exception {   
           IMOperation op = new IMOperation();
            op.addImage();                       
            op.resize(350)
            op.addImage("jpg:-")               
            BufferedImage images = ImageIO.read(new File("image.jpg")); 

            // set up command
            ConvertCmd convert = new ConvertCmd();
            Stream2BufferedImage s2b = new Stream2BufferedImage();
            convert.setOutputConsumer(s2b);

            // run command and extract BufferedImage from OutputConsumer
            convert.run(op,images);
            BufferedImage img = s2b.getImage();
        }