Java Code Examples for java.awt.Image#getHeight()

The following examples show how to use java.awt.Image#getHeight() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PathGraphics.java    From jdk8u-dev-jdk with GNU General Public License v2.0 8 votes vote down vote up
public boolean drawImage(Image img, int x, int y,
                         Color bgcolor,
                         ImageObserver observer) {

    if (img == null) {
        return true;
    }

    boolean result;
    int srcWidth = img.getWidth(null);
    int srcHeight = img.getHeight(null);

    if (srcWidth < 0 || srcHeight < 0) {
        result = false;
    } else {
        result = drawImage(img, x, y, srcWidth, srcHeight, bgcolor, observer);
    }

    return result;
}
 
Example 2
Source File: PathGraphics.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public boolean drawImage(Image img, int x, int y,
                         Color bgcolor,
                         ImageObserver observer) {

    if (img == null) {
        return true;
    }

    boolean result;
    int srcWidth = img.getWidth(null);
    int srcHeight = img.getHeight(null);

    if (srcWidth < 0 || srcHeight < 0) {
        result = false;
    } else {
        result = drawImage(img, x, y, srcWidth, srcHeight, bgcolor, observer);
    }

    return result;
}
 
Example 3
Source File: PeekGraphics.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
synchronized private void waitForDimensions(Image img) {
    mHeight = img.getHeight(this);
    mWidth = img.getWidth(this);
    while (!badImage && (mWidth < 0 || mHeight < 0)) {
        try {
            Thread.sleep(50);
        } catch(InterruptedException e) {
            // do nothing.
        }
        mHeight = img.getHeight(this);
        mWidth = img.getWidth(this);
    }
    if (badImage) {
        mHeight = 0;
        mWidth = 0;
    }
}
 
Example 4
Source File: IncorrectUnmanagedImageRotatedClip.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void fill(final Image image) {
    final Graphics2D graphics = (Graphics2D) image.getGraphics();
    graphics.setComposite(AlphaComposite.Src);
    for (int i = 0; i < image.getHeight(null); ++i) {
        graphics.setColor(new Color(i, 0, 0));
        graphics.fillRect(0, i, image.getWidth(null), 1);
    }
    graphics.dispose();
}
 
Example 5
Source File: StatusMessageImageConverter.java    From WorldGrower with GNU General Public License v3.0 5 votes vote down vote up
public static Image convertImage(Image image) {
	int imageWidth = image.getWidth(null);
	int imageHeight = image.getHeight(null);
	if (imageWidth > 48 || imageHeight > 48) {
		int croppedImageWidth = Math.min(48, imageWidth);
		int croppedImageHeight = Math.min(48, imageHeight);
		image = ImageUtils.cropImage((BufferedImage) image, croppedImageWidth, croppedImageHeight);
	}
	return image;
}
 
Example 6
Source File: UnitImageFactory.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
private static BufferedImage convertToBufferedImage(final Image image) {
  final BufferedImage newImage =
      new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
  final Graphics2D g = newImage.createGraphics();
  g.drawImage(image, 0, 0, null);
  g.dispose();
  return newImage;
}
 
Example 7
Source File: SimpleUnmanagedImage.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void fill(final Image image) {
    final Graphics2D graphics = (Graphics2D) image.getGraphics();
    graphics.setComposite(AlphaComposite.Src);
    for (int i = 0; i < image.getHeight(null); ++i) {
        graphics.setColor(new Color(i, 0, 0));
        graphics.fillRect(0, i, image.getWidth(null), 1);
    }
    graphics.dispose();
}
 
Example 8
Source File: NSImageToMultiResolutionImageTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        if (OSInfo.getOSType() != OSInfo.OSType.MACOSX) {
            return;
        }

        String icon = "NSImage://NSApplicationIcon";
        final Image image = Toolkit.getDefaultToolkit().getImage(icon);

        if (!(image instanceof MultiResolutionImage)) {
            throw new RuntimeException("Icon does not have resolution variants!");
        }

        MultiResolutionImage multiResolutionImage = (MultiResolutionImage) image;

        int width = 0;
        int height = 0;

        for (Image resolutionVariant : multiResolutionImage.getResolutionVariants()) {
            int rvWidth = resolutionVariant.getWidth(null);
            int rvHeight = resolutionVariant.getHeight(null);
            if (rvWidth < width || rvHeight < height) {
                throw new RuntimeException("Resolution variants are not sorted!");
            }
            width = rvWidth;
            height = rvHeight;
        }
    }
 
Example 9
Source File: SunGraphics2D.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Draws an image at x,y in nonblocking mode with a solid background
 * color and a callback object.
 */
public boolean drawImage(Image img, int x, int y, Color bg,
                         ImageObserver observer) {

    if (img == null) {
        return true;
    }

    if (isHiDPIImage(img)) {
        final int imgW = img.getWidth(null);
        final int imgH = img.getHeight(null);
        return drawHiDPIImage(img, x, y, x + imgW, y + imgH, 0, 0, imgW,
                              imgH, bg, observer);
    }

    try {
        return imagepipe.copyImage(this, img, x, y, bg, observer);
    } catch (InvalidPipeException e) {
        try {
            revalidateAll();
            return imagepipe.copyImage(this, img, x, y, bg, observer);
        } catch (InvalidPipeException e2) {
            // Still catching the exception; we are not yet ready to
            // validate the surfaceData correctly.  Fail for now and
            // try again next time around.
            return false;
        }
    } finally {
        surfaceData.markDirty();
    }
}
 
Example 10
Source File: ImageUtils.java    From GpsPrune with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a new image by rotating and scaling the given one
 * @param inImage input image
 * @param inMaxWidth maximum width of output image
 * @param inMaxHeight maximum height of output image
 * @param inRotationDegrees number of degrees to rotate clockwise (0, 90, 180 or 270)
 * @return rotated, scaled image
 */
public static BufferedImage rotateImage(Image inImage, int inMaxWidth, int inMaxHeight, int inRotationDegrees)
{
	// Create scaled image of suitable size
	boolean isRotated = (inRotationDegrees % 180 != 0);
	int origWidth = inImage.getWidth(null);
	int origHeight = inImage.getHeight(null);
	int thumbWidth = isRotated?origHeight:origWidth;
	int thumbHeight = isRotated?origWidth:origHeight;
	Dimension scaledSize = getThumbnailSize(thumbWidth, thumbHeight, inMaxWidth, inMaxHeight);
	BufferedImage result = new BufferedImage(scaledSize.width, scaledSize.height, BufferedImage.TYPE_INT_RGB);
	// Do different things according to rotation angle (a bit messy, sorry!)
	if (inRotationDegrees == 0)
	{
		// Not rotated, so just copy image directly
		result.getGraphics().drawImage(inImage, 0, 0, scaledSize.width, scaledSize.height, null);
	}
	else
	{
		// Need to use Graphics2D for rotation, not Graphics
		Graphics2D g2d = result.createGraphics();
		switch (inRotationDegrees)
		{
			case 90:
				g2d.rotate(Math.PI / 2, 0.0, 0.0);
				g2d.drawImage(inImage, 0, -scaledSize.width, scaledSize.height, scaledSize.width, null);
				break;
			case 180:
				g2d.rotate(Math.PI, scaledSize.width/2.0, scaledSize.height/2.0);
				g2d.drawImage(inImage, 0, 0, scaledSize.width, scaledSize.height, null);
				break;
			case 270:
				g2d.rotate(Math.PI * 3/2, 0.0, 0.0);
				g2d.drawImage(inImage, -scaledSize.height, 0, scaledSize.height, scaledSize.width, null);
		}
		// Clear up memory
		g2d.dispose();
	}
	return result;
}
 
Example 11
Source File: ImageUtil.java    From oim-fx with MIT License 5 votes vote down vote up
/**
 * 添加图片水印
 *
 * @param targetImg 目标图片路径,如:C://myPictrue//1.jpg
 * @param waterImg 水印图片路径,如:C://myPictrue//logo.png
 * @param x 水印图片距离目标图片左侧的偏移量,如果x<0, 则在正中间 @ param y 水印图片距离目标图片上侧的偏移量,如果y<0,
 * 则在正中间 @ param alpha 透明度(0.0 -- 1.0, 0.0为完全透明,1.0为完全不透明)
 */
public static void pressImage(String targetImg, String waterImg, int x, int y, float alpha) {
    try {
        File file = new File(targetImg);
        Image image = ImageIO.read(file);
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufferedImage.createGraphics();
        g.drawImage(image, 0, 0, width, height, null);

        Image waterImage = ImageIO.read(new File(waterImg)); // 水印文件
        int width_1 = waterImage.getWidth(null);
        int height_1 = waterImage.getHeight(null);
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));

        int widthDiff = width - width_1;
        int heightDiff = height - height_1;
        if (x < 0) {
            x = widthDiff / 2;
        } else if (x > widthDiff) {
            x = widthDiff;
        }
        if (y < 0) {
            y = heightDiff / 2;
        } else if (y > heightDiff) {
            y = heightDiff;
        }
        g.drawImage(waterImage, x, y, width_1, height_1, null); // 水印文件结束
        g.dispose();
        ImageIO.write(bufferedImage, PICTRUE_FORMATE_JPG, file);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 12
Source File: SimpleManagedImage.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void fill(final Image image) {
    final Graphics2D graphics = (Graphics2D) image.getGraphics();
    graphics.setComposite(AlphaComposite.Src);
    for (int i = 0; i < image.getHeight(null); ++i) {
        graphics.setColor(new Color(i, 0, 0));
        graphics.fillRect(0, i, image.getWidth(null), 1);
    }
    graphics.dispose();
}
 
Example 13
Source File: TranslucentWindowPainter.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private static final Image clearImage(Image bb) {
    Graphics2D g = (Graphics2D)bb.getGraphics();
    int w = bb.getWidth(null);
    int h = bb.getHeight(null);

    g.setComposite(AlphaComposite.Src);
    g.setColor(new Color(0, 0, 0, 0));
    g.fillRect(0, 0, w, h);

    return bb;
}
 
Example 14
Source File: WDragSourceContextPeer.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected void startDrag(Transferable trans,
                         long[] formats, Map<Long, DataFlavor> formatMap) {

    long nativeCtxtLocal = 0;

    nativeCtxtLocal = createDragSource(getTrigger().getComponent(),
                                       trans,
                                       getTrigger().getTriggerEvent(),
                                       getTrigger().getSourceAsDragGestureRecognizer().getSourceActions(),
                                       formats,
                                       formatMap);

    if (nativeCtxtLocal == 0) {
        throw new InvalidDnDOperationException("failed to create native peer");
    }

    int[] imageData = null;
    Point op = null;

    Image im = getDragImage();
    int imageWidth = -1;
    int imageHeight = -1;
    if (im != null) {
        //image is ready (partial images are ok)
        try{
            imageWidth = im.getWidth(null);
            imageHeight = im.getHeight(null);
            if (imageWidth < 0 || imageHeight < 0) {
                throw new InvalidDnDOperationException("drag image is not ready");
            }
            //We could get an exception from user code here.
            //"im" and "dragImageOffset" are user-defined objects
            op = getDragImageOffset(); //op could not be null here
            BufferedImage bi = new BufferedImage(
                    imageWidth,
                    imageHeight,
                    BufferedImage.TYPE_INT_ARGB);
            bi.getGraphics().drawImage(im, 0, 0, null);

            //we can get out-of-memory here
            imageData = ((DataBufferInt)bi.getData().getDataBuffer()).getData();
        } catch (Throwable ex) {
            throw new InvalidDnDOperationException("drag image creation problem: " + ex.getMessage());
        }
    }

    //We shouldn't have user-level exceptions since now.
    //Any exception leads to corrupted D'n'D state.
    setNativeContext(nativeCtxtLocal);
    WDropTargetContextPeer.setCurrentJVMLocalSourceTransferable(trans);

    if (imageData != null) {
        doDragDrop(
                getNativeContext(),
                getCursor(),
                imageData,
                imageWidth, imageHeight,
                op.x, op.y);
    } else {
        doDragDrop(
                getNativeContext(),
                getCursor(),
                null,
                -1, -1,
                0, 0);
    }
}
 
Example 15
Source File: SunGraphics2D.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Draws an image scaled to x,y,w,h in nonblocking mode with a
 * solid background color and a callback object.
 */
public boolean drawImage(Image img, int x, int y, int width, int height,
                         Color bg, ImageObserver observer) {

    if (img == null) {
        return true;
    }

    if ((width == 0) || (height == 0)) {
        return true;
    }

    final int imgW = img.getWidth(null);
    final int imgH = img.getHeight(null);
    if (isHiDPIImage(img)) {
        return drawHiDPIImage(img, x, y, x + width, y + height, 0, 0, imgW,
                              imgH, bg, observer);
    }

    if (width == imgW && height == imgH) {
        return copyImage(img, x, y, 0, 0, width, height, bg, observer);
    }

    try {
        return imagepipe.scaleImage(this, img, x, y, width, height,
                                    bg, observer);
    } catch (InvalidPipeException e) {
        try {
            revalidateAll();
            return imagepipe.scaleImage(this, img, x, y, width, height,
                                        bg, observer);
        } catch (InvalidPipeException e2) {
            // Still catching the exception; we are not yet ready to
            // validate the surfaceData correctly.  Fail for now and
            // try again next time around.
            return false;
        }
    } finally {
        surfaceData.markDirty();
    }
}
 
Example 16
Source File: ImageCache.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Sets the cached image for the specified constraints.
 *
 * @param image  The image to store in cache
 * @param config The graphics configuration, needed if cached image is a Volatile Image. Used as part of cache key
 * @param w      The image width, used as part of cache key
 * @param h      The image height, used as part of cache key
 * @param args   Other arguments to use as part of the cache key
 * @return true if the image could be cached or false if the image is too big
 */
public boolean setImage(Image image, GraphicsConfiguration config, int w, int h, Object... args) {
    if (!isImageCachable(w, h)) return false;
    int hash = hash(config, w, h, args);
    lock.writeLock().lock();
    try {
        PixelCountSoftReference ref = map.get(hash);
        // check if currently in map
        if (ref != null && ref.get() == image) {
            return true;
        }
        // clear out old
        if (ref != null) {
            currentPixelCount -= ref.pixelCount;
            map.remove(hash);
        }
        // add new image to pixel count
        int newPixelCount = image.getWidth(null) * image.getHeight(null);
        currentPixelCount += newPixelCount;
        // clean out lost references if not enough space
        if (currentPixelCount > maxPixelCount) {
            while ((ref = (PixelCountSoftReference)referenceQueue.poll()) != null){
                //reference lost
                map.remove(ref.hash);
                currentPixelCount -= ref.pixelCount;
            }
        }
        // remove old items till there is enough free space
        if (currentPixelCount > maxPixelCount) {
            Iterator<Map.Entry<Integer, PixelCountSoftReference>> mapIter = map.entrySet().iterator();
            while ((currentPixelCount > maxPixelCount) && mapIter.hasNext()) {
                Map.Entry<Integer, PixelCountSoftReference> entry = mapIter.next();
                mapIter.remove();
                Image img = entry.getValue().get();
                if (img != null) img.flush();
                currentPixelCount -= entry.getValue().pixelCount;
            }
        }
        // finaly put new in map
        map.put(hash, new PixelCountSoftReference(image, referenceQueue, newPixelCount,hash, config, w, h, args));
        return true;
    } finally {
        lock.writeLock().unlock();
    }
}
 
Example 17
Source File: ImageView.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns true if the passed in image has a non-zero width and height.
 */
private boolean hasPixels(Image image) {
    return image != null &&
        (image.getHeight(imageObserver) > 0) &&
        (image.getWidth(imageObserver) > 0);
}
 
Example 18
Source File: MultiResolutionImageTest.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
static void testToolkitMultiResolutionImage(Image image, boolean enableImageScaling)
        throws Exception {

    MediaTracker tracker = new MediaTracker(new JPanel());
    tracker.addImage(image, 0);
    tracker.waitForID(0);
    if (tracker.isErrorAny()) {
        throw new RuntimeException("Error during image loading");
    }

    final BufferedImage bufferedImage1x = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT,
            BufferedImage.TYPE_INT_RGB);
    Graphics2D g1x = (Graphics2D) bufferedImage1x.getGraphics();
    setImageScalingHint(g1x, false);
    g1x.drawImage(image, 0, 0, null);
    checkColor(bufferedImage1x.getRGB(3 * IMAGE_WIDTH / 4, 3 * IMAGE_HEIGHT / 4), false);

    Image resolutionVariant = ((MultiResolutionImage) image).
            getResolutionVariant(2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT);

    if (resolutionVariant == null) {
        throw new RuntimeException("Resolution variant is null");
    }

    MediaTracker tracker2x = new MediaTracker(new JPanel());
    tracker2x.addImage(resolutionVariant, 0);
    tracker2x.waitForID(0);
    if (tracker2x.isErrorAny()) {
        throw new RuntimeException("Error during scalable image loading");
    }

    final BufferedImage bufferedImage2x = new BufferedImage(2 * IMAGE_WIDTH,
            2 * IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2x = (Graphics2D) bufferedImage2x.getGraphics();
    setImageScalingHint(g2x, enableImageScaling);
    g2x.drawImage(image, 0, 0, 2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, null);
    checkColor(bufferedImage2x.getRGB(3 * IMAGE_WIDTH / 2, 3 * IMAGE_HEIGHT / 2), enableImageScaling);

    if (!(image instanceof MultiResolutionImage)) {
        throw new RuntimeException("Not a MultiResolutionImage");
    }

    MultiResolutionImage multiResolutionImage = (MultiResolutionImage) image;

    Image image1x = multiResolutionImage.getResolutionVariant(IMAGE_WIDTH, IMAGE_HEIGHT);
    Image image2x = multiResolutionImage.getResolutionVariant(2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT);

    if (image1x.getWidth(null) * 2 != image2x.getWidth(null)
            || image1x.getHeight(null) * 2 != image2x.getHeight(null)) {
        throw new RuntimeException("Wrong resolution variant size");
    }
}
 
Example 19
Source File: SunGraphics2D.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Draw an image, applying a transform from image space into user space
 * before drawing.
 * The transformation from user space into device space is done with
 * the current transform in the Graphics2D.
 * The given transformation is applied to the image before the
 * transform attribute in the Graphics2D state is applied.
 * The rendering attributes applied include the clip, transform,
 * paint or color and composite attributes. Note that the result is
 * undefined, if the given transform is non-invertible.
 * @param img The image to be drawn.
 * @param xform The transformation from image space into user space.
 * @param observer The image observer to be notified on the image producing
 * progress.
 * @see #transform
 * @see #setComposite
 * @see #setClip
 */
public boolean drawImage(Image img,
                         AffineTransform xform,
                         ImageObserver observer) {

    if (img == null) {
        return true;
    }

    if (xform == null || xform.isIdentity()) {
        return drawImage(img, 0, 0, null, observer);
    }

    if (isHiDPIImage(img)) {
        final int w = img.getWidth(null);
        final int h = img.getHeight(null);
        final AffineTransform tx = new AffineTransform(transform);
        transform(xform);
        boolean result = drawHiDPIImage(img, 0, 0, w, h, 0, 0, w, h, null,
                                        observer);
        transform.setTransform(tx);
        invalidateTransform();
        return result;
    }

    try {
        return imagepipe.transformImage(this, img, xform, observer);
    } catch (InvalidPipeException e) {
        try {
            revalidateAll();
            return imagepipe.transformImage(this, img, xform, observer);
        } catch (InvalidPipeException e2) {
            // Still catching the exception; we are not yet ready to
            // validate the surfaceData correctly.  Fail for now and
            // try again next time around.
            return false;
        }
    } finally {
        surfaceData.markDirty();
    }
}
 
Example 20
Source File: ScaleImageUtils.java    From FlyCms with MIT License 4 votes vote down vote up
public static int[] getSizeByHeight(int height, Image image) {
    int targetWidth = image.getWidth(null);
    int targetHeight = image.getHeight(null);
    long width = Math.round((targetWidth * height) / (targetHeight * 1.00f));
    return new int[] { Integer.parseInt(String.valueOf(width)), height };
}