通过画布缩放后,BufferedImage变为全黑

时间:2011-10-12 10:24:05

标签: java image bufferedimage

我有一个方法,其目的是接收图像并将其缩小。 我使用画布的原因是我相信它会自动缩放图像。

转换后,outputimage完全变黑。任何人都知道如何解决这个问题?

try {
        InputStream in = new ByteArrayInputStream(f.getBytes());
        BufferedImage image = ImageIO.read(in);

        File beforescale = new File("beforescale.jpg");
        ImageIO.write(image, "jpg", beforescale);  //works

        Canvas canvas = new Canvas();
        canvas.setSize(100, 100);
        canvas.paint(image.getGraphics());

        image = canvasToImage(canvas);
        File outputfile = new File("testing.jpg");
        ImageIO.write(image, "jpg", outputfile); //all black

        response.getWriter().print(canvas);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

private BufferedImage canvasToImage(Canvas cnvs) {
    int w = cnvs.getWidth();
    int h = cnvs.getHeight();
    int type = BufferedImage.TYPE_INT_RGB;
    BufferedImage image = new BufferedImage(w,h,type);
    Graphics2D g2 = image.createGraphics();
    cnvs.paint(g2);
    g2.dispose();
    return image;
}

1 个答案:

答案 0 :(得分:2)

问题是,在这里你使用canvas#paint(Graphics)在画布上绘制图像

    canvas.paint(image.getGraphics());

在这里你再次绘制#paint(Graphics)来绘制图像上的画布

    cnvs.paint(g2);

显然这两个中的一个失败了。您只能使用此方法在图像上绘制画布。

解决方案是在image上使用getScaledInstance()

BufferedImage image = ImageIO.read(in);
Image smallerImg = image.getScaledInstance(100,100,Image.SCALE_SMOOTH);
ImageIO.write(smallerImg, "jpg", outputfile);