How to use ImageObserver in Graphics method drawImage()

孤人 提交于 2019-12-05 04:23:15

Unless the class in which you are calling Graphics.drawImage(Image, int, int, int, int, ImageObserver) is an ImageObserver, using this as the argument for the ImageObserver will not work:

class MyClass {
  public void resizeImage() {
    Graphics g = getGraphicsObjectFromSomewhere();

    // The following line will not compile, as `MyClass` 
    // does not implement `ImageObserver`.
    g.drawImage(img, 0, 0, 50, 50, this);
  }
}

If you're resizing an image which does not require an ImageObserver (such as a BufferedImage that already contains the image you want to resize), then you can just hand over a null:

// The image we want to resize
BufferedImage img = ImageIO.read("some-image.jpg");

// The Graphics object of the destination
// -- this will probably just be obtained from the destination image.
Graphics g = getGraphicsObjectFromSomewhere();

// Perform the resizing. Hand a `null` for the ImageObserver,
// as we don't need one.
g.drawImage(img, 0, 0, 50, 50, null);

That said, I'm going to throw in a little plug for my image resizing library Thumbnailator.

If all that is required is to resize an image, it can be accomplished as simple as the following code:

Thumbnails.of("path/to/image")
  .size(100, 100)
  .toFile("path/to/thumbnail");

Thumbnailator is flexible enough to accept BufferedImages, Files, and InputStreams as input.


Seeing your edit, I would suggest to change the Hitter class, so that it will perform the resizing of the image in the constructor.

Since you are calling the drawHitter method on each call from the Applet.drawImage, the resize operation using Graphics.drawImage is being called many times, even when the hitterWidth and hitterHeight are, for all intents and purposes, constants.

Resizing the Image ahead of time, and drawing that pre-resized image in the drawHitter method will be more efficient.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!