简体   繁体   中英

BufferedImage turns all black after scaling via canvas

I have a method which purpose is to receive an image and return it scaled down. The reason I'm using canvas is that I believe that it will scale the image automatically for me.

After the conversion the outputimage is completely black. Anyone have any clue on how to fix this?

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

The problem is, here you use canvas#paint(Graphics) to paint the image on the canvas :

    canvas.paint(image.getGraphics());

And here you canvas#paint(Graphics) again to paint the canvas on the image :

    cnvs.paint(g2);

Obviously one of these two fails. You can only use this method to paint the canvas on the image.

The solution is to use getScaledInstance() on image .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM