0

I am having a problem with the Grapics2D API, I am trying to re-size an image but instead of getting the smaller image its showing a half white and half grey area. what am I doing wrong? I tried with and without render hints and it didn't work, or is there another approach that will give me a new Buffered Image object at the specified size?

//height = 400, width = 600, capture_rect = screen size
BufferedImage img = robot.createScreenCapture(CAPTURE_RECT);
BufferedImage resized = new BufferedImage(WIDTH, HEIGHT, img.getType());
Graphics2D g = resized.createGraphics();
g.drawImage(img, 0, 0, WIDTH, HEIGHT, 0, 0, img.getWidth(), img.getHeight(), null);
g.dispose();
setImage(resized);

1 Answers1

2

See the article on Perils of Image.getScaledImage. It has some recommendations.

Here is some code it recommends:

private float xScaleFactor, yScaleFactor = ...;
private BufferedImage originalImage = ...;

public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D)g;
    int newW = (int)(originalImage.getWidth() * xScaleFactor);
    int newH = (int)(originalImage.getHeight() * yScaleFactor);
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                        RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(originalImage, 0, 0, newW, newH, null);
}

It looks like you just need to specify the new width/height and it will do the scaling for you automatically.

Or maybe the problem is with the img.getType() method. You should be able to just using:

BufferedImage.TYPE_INT_RGB // (or ARGB)

See which works the best.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • I am not trying to get the scaled image painted to the object, I am trying to get a new BufferedImage object that has been scaled –  Apr 23 '13 at 01:55
  • I was giving you example code that you should be able to modify to do what you want. That is I was showing you a different way to use the drawImage() method with 5 parameters instead of the parameters you specified. – camickr Apr 23 '13 at 04:13