import java.awt.*;
import java.awt.image.*;

/** Contains utility methods for working with Image objects. */
public class ImageUtil {
	private ImageUtil() { }

	private static class ImgDims implements ImageObserver {
		private int width = -1;
		private int height = -1;

		public synchronized void setWidth(int w) {
			if(w >= 0) { width = w; notifyAll(); }
		}

		public synchronized void setHeight(int h) {
			if(h >= 0) { height = h; notifyAll(); }
		}

		public synchronized int getWidth() {
			try {
				while(width < 0) wait();
				return width;
			} catch(InterruptedException e) { return -1; }
		}

		public synchronized int getHeight() {
			try {
				while(height < 0) wait();
				return height;
			} catch(InterruptedException e) { return -1; }
		}

		public boolean imageUpdate(Image img,
				int infoflags, int x, int y, int w, int h) {
			if((infoflags & WIDTH) != 0) setWidth(w);
			if((infoflags & HEIGHT) != 0) setHeight(h);
			return !(width >= 0 && height >= 0);
		}
	}

	/** Returns the width and height of the given image within
	 * a java.awt.Dimension object. */
	public static Dimension getDimension(Image img) {
		ImgDims observer = new ImgDims();
		observer.setWidth(img.getWidth(observer));
		observer.setHeight(img.getHeight(observer));
		return new Dimension(observer.getWidth(), observer.getHeight());
	}
}
