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

The following are Jave code examples for showing how to use getHeight() of the java.awt.Image class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: stock-api-sdk   File: ApiUtils.java   View Source Code Vote up 7 votes
/**
 * Converts a given Image into a BufferedImage.
 *
 * @param img The Image to be converted
 * @return The converted BufferedImage
 */
private static BufferedImage toBufferedImage(final Image img) {
    BufferedImage bimage = new BufferedImage(img.getWidth(null),
            img.getHeight(null), BufferedImage.TYPE_INT_RGB);

    // Draw the image on to the buffered image
    Graphics2D g2 = bimage.createGraphics();
    boolean x = false;
    while (!x) {
        x = g2.drawImage(img, 0, 0, null);
    }
    g2.dispose();

    // Return the buffered image
    return bimage;
}
 
Example 2
Project: raven   File: ImageUtils.java   View Source Code Vote up 6 votes
/**
 * 灏嗗浘鐗囦互height涓哄噯杩涜绛夋瘮缂╂斁銆�
 * 
 * @param imageBytes
 * @param height
 * @param imageFormatName
 * @return
 */
public static byte[] scaleImageByHeight(byte[] imageBytes, int height,
		String imageFormatName) {
	Image img = null;
	int width = 0;
	try {
		img = ImageIO.read(new ByteArrayInputStream(imageBytes));
		int old_w = img.getWidth(null);
		int old_h = img.getHeight(null);
		if (old_h > 0 && old_w > 0) {
			// 浠ラ珮搴︿负鍑嗭紝璁$畻瀹藉害 绛夋瘮缂╂斁
			width = (int) ((float) height / old_h * old_w);
		}
	} catch (Exception e) {
		logger.error("scaleImageByHeight faild!", e);
	}
	return ImageUtils.scaleImage(imageBytes, width, height,
			Image.SCALE_SMOOTH, imageFormatName);
}
 
Example 3
Project: OpenJSharp   File: PeekGraphics.java   View Source Code Vote up 6 votes
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
Project: openjdk-jdk10   File: MultiResolutionImageTest.java   View Source Code Vote up 6 votes
static void testToolkitMultiResolutionImageLoad(Image image)
    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");
    }
    tracker.removeImage(image, 0);

    testImageLoaded(image);

    int w = image.getWidth(null);
    int h = image.getHeight(null);

    Image resolutionVariant = ((MultiResolutionImage) image)
        .getResolutionVariant(2 * w, 2 * h);

    if (image == resolutionVariant) {
        throw new RuntimeException("Resolution variant is not loaded");
    }

    testImageLoaded(resolutionVariant);
}
 
Example 5
Project: Java-Algorithms-Learning   File: StdDraw.java   View Source Code Vote up 6 votes
/**
 * Draws the specified image centered at (<em>x</em>, <em>y</em>),
 * rotated given number of degrees.
 * The supported image formats are JPEG, PNG, and GIF.
 *
 * @param  x the center <em>x</em>-coordinate of the image
 * @param  y the center <em>y</em>-coordinate of the image
 * @param  filename the name of the image/picture, e.g., "ball.gif"
 * @param  degrees is the number of degrees to rotate counterclockwise
 * @throws IllegalArgumentException if the image filename is invalid
 */
public static void picture(double x, double y, String filename, double degrees) {
    // BufferedImage image = getImage(filename);
    Image image = getImage(filename);
    double xs = scaleX(x);
    double ys = scaleY(y);
    // int ws = image.getWidth();    // can call only if image is a BufferedImage
    // int hs = image.getHeight();
    int ws = image.getWidth(null);
    int hs = image.getHeight(null);
    if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + filename + " is corrupt");

    offscreen.rotate(Math.toRadians(-degrees), xs, ys);
    offscreen.drawImage(image, (int) Math.round(xs - ws/2.0), (int) Math.round(ys - hs/2.0), null);
    offscreen.rotate(Math.toRadians(+degrees), xs, ys);

    draw();
}
 
Example 6
Project: AdvancedServerListIcons   File: ImageHandler.java   View Source Code Vote up 5 votes
private BufferedImage toBufferedImage(Image image) {
    if (image instanceof BufferedImage) {
        return (BufferedImage) image;
    }
    BufferedImage buffer = new BufferedImage(image.getWidth(null), image.getHeight(null), 2);
    Graphics2D g = buffer.createGraphics();
    g.drawImage(image, null, null);
    image.flush();
    return buffer;
}
 
Example 7
Project: myfaces-trinidad   File: CompositeButtonPainter.java   View Source Code Vote up 5 votes
private Dimension _getImageSize(
  PaintContext context,
  Image        image
  )
{
  if (image == null)
    return new Dimension(0,0);

  ImageObserver observer = context.getImageObserver();

  return new Dimension(image.getWidth(observer),
                       image.getHeight(observer));
}
 
Example 8
Project: FreeCol   File: ImageLibrary.java   View Source Code Vote up 5 votes
public static BufferedImage createMirroredImage(Image image) {
    if(image == null)
        return null;
    final int width = image.getWidth(null);
    final int height = image.getHeight(null);
    BufferedImage result = new BufferedImage(width, height,
        BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = result.createGraphics();
    g.drawImage(image, width, 0, -width, height, null);
    g.dispose();
    return result;
}
 
Example 9
Project: TestDemo1-github   File: ThumbnailGenerator.java   View Source Code Vote up 5 votes
public void transform(String originalFile, String thumbnailFile, int thumbWidth, int thumbHeight, int quality) throws Exception 
{
	Image image = javax.imageio.ImageIO.read(new File(originalFile));
    
    double thumbRatio = (double)thumbWidth / (double)thumbHeight;
    int imageWidth    = image.getWidth(null);
    int imageHeight   = image.getHeight(null);
    double imageRatio = (double)imageWidth / (double)imageHeight;
    if (thumbRatio < imageRatio) 
    {
    	thumbHeight = (int)(thumbWidth / imageRatio);
    } 
    else 
    {
      	thumbWidth = (int)(thumbHeight * imageRatio);
    }
    
	if(imageWidth < thumbWidth && imageHeight < thumbHeight)
	{
		thumbWidth = imageWidth;
		thumbHeight = imageHeight;
	}
	else if(imageWidth < thumbWidth)
		thumbWidth = imageWidth;
	else if(imageHeight < thumbHeight)
		thumbHeight = imageHeight;

    BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics2D = thumbImage.createGraphics();
    graphics2D.setBackground(Color.WHITE);
   	graphics2D.setPaint(Color.WHITE); 
   	graphics2D.fillRect(0, 0, thumbWidth, thumbHeight);
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
    
	javax.imageio.ImageIO.write(thumbImage, "JPG", new File(thumbnailFile));
}
 
Example 10
Project: myster   File: TabUtilities.java   View Source Code Vote up 5 votes
private static Image makeTransparent(Component c, Image workingImage) {
    int[] array =
            getPixels(workingImage, 0, 0, workingImage.getWidth(c), workingImage.getHeight(c));

    for (int i = 0; i < array.length; i++) {
        array[i] = makeWhiteTransparent(array[i]);
    }

    MemoryImageSource source = new MemoryImageSource(workingImage.getWidth(c),
                                                     workingImage.getHeight(c),
                                                     array,
                                                     0,
                                                     workingImage.getWidth(c));
    return c.createImage(source);
}
 
Example 11
Project: rapidminer   File: Tools.java   View Source Code Vote up 5 votes
public static ImageIcon getBigSystemIcon(Image image) throws Exception {
	if (image.getWidth(null) < 20 || image.getHeight(null) < 20) {
		if (image.getWidth(null) > image.getHeight(null)) {
			width = 24;
			height = image.getHeight(null) * 24 / image.getWidth(null);
		} else {
			height = 24;
			width = image.getWidth(null) * 24 / image.getHeight(null);
		}
	} else {
		return new ImageIcon(image);
	}

	dest = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
	dest2 = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);

	g = dest.getGraphics();
	g.setColor(Color.white);
	g.fillRect(0, 0, 22, 22);
	g.drawImage(image, 0, 0, width, height, null);

	g.dispose();

	sharpenOperator.filter(dest, dest2);

	return new ImageIcon(dest);
}
 
Example 12
Project: ameliaclient   File: ConnectorThread.java   View Source Code Vote up 5 votes
private static BufferedImage toBufferedImage(Image img){
    if (img instanceof BufferedImage){
        return (BufferedImage) img;
    }

    BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.SCALE_SMOOTH);

    Graphics2D bGr = bimage.createGraphics();
    bGr.drawImage(img, 0, 0, null);
    bGr.dispose();

    return bimage;
}
 
Example 13
Project: FreeCol   File: ImageLibrary.java   View Source Code Vote up 5 votes
/**
 * Creates a buffered image out of a given {@code Image} object.
 * 
 * @param image The {@code Image} object.
 * @return The created {@code BufferedImage} object.
 */
public static BufferedImage createBufferedImage(Image image) {
    if(image == null)
        return null;
    BufferedImage result = new BufferedImage(image.getWidth(null),
        image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = result.createGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();
    return result;
}
 
Example 14
Project: BrainControl   File: Art.java   View Source Code Vote up 5 votes
private static SpriteSheet cutImage(GraphicsConfiguration gc, String imageName, int xSize, int ySize) throws IOException 
{
	xSize*=GlobalOptions.resolution_factor;
	ySize*=GlobalOptions.resolution_factor;
			
	Image source = getImage(gc, imageName);		
			
	Image[][] cutsource = new Image[source.getWidth(null) / xSize][source.getHeight(null) / ySize];		
	
	for (int x = 0; x < source.getWidth(null) / xSize; x++) 
	{
		for (int y = 0; y < source.getHeight(null) / ySize; y++) 
		{
			Image image = gc.createCompatibleImage(xSize, ySize, Transparency.TRANSLUCENT);
			Graphics2D g = (Graphics2D) image.getGraphics();
							
			//g.setComposite(AlphaComposite.Src);
			
			//ENABLE PARTIAL TRANSPARENCY
			AlphaComposite ac = java.awt.AlphaComposite.getInstance(AlphaComposite.SRC);
	        g.setComposite(ac);						
			
			g.drawImage(source, -x * xSize, -y * ySize, null);
			g.dispose();
			
			cutsource[x][y] = image;
		}
	}		
	
	System.out.println(imageName);
	SpriteSheet ret = new SpriteSheet(xSize, ySize, source.getWidth(null) / xSize, source.getHeight(null) / ySize, cutsource);
	
	return ret;
}
 
Example 15
Project: OpenJSharp   File: SunGraphics2D.java   View Source Code Vote up 4 votes
private boolean drawHiDPIImage(Image img, int dx1, int dy1, int dx2,
                               int dy2, int sx1, int sy1, int sx2, int sy2,
                               Color bgcolor, ImageObserver observer) {

    if (SurfaceManager.getImageScale(img) != 1) {  // Volatile Image
        final int scale = SurfaceManager.getImageScale(img);
        sx1 = Region.clipScale(sx1, scale);
        sx2 = Region.clipScale(sx2, scale);
        sy1 = Region.clipScale(sy1, scale);
        sy2 = Region.clipScale(sy2, scale);
    } else if (img instanceof MultiResolutionImage) {
        // get scaled destination image size

        int width = img.getWidth(observer);
        int height = img.getHeight(observer);

        Image resolutionVariant = getResolutionVariant(
                (MultiResolutionImage) img, width, height,
                dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2);

        if (resolutionVariant != img && resolutionVariant != null) {
            // recalculate source region for the resolution variant

            ImageObserver rvObserver = MultiResolutionToolkitImage.
                    getResolutionVariantObserver(img, observer,
                            width, height, -1, -1);

            int rvWidth = resolutionVariant.getWidth(rvObserver);
            int rvHeight = resolutionVariant.getHeight(rvObserver);

            if (0 < width && 0 < height && 0 < rvWidth && 0 < rvHeight) {

                float widthScale = ((float) rvWidth) / width;
                float heightScale = ((float) rvHeight) / height;

                sx1 = Region.clipScale(sx1, widthScale);
                sy1 = Region.clipScale(sy1, heightScale);
                sx2 = Region.clipScale(sx2, widthScale);
                sy2 = Region.clipScale(sy2, heightScale);

                observer = rvObserver;
                img = resolutionVariant;
            }
        }
    }

    try {
        return imagepipe.scaleImage(this, img, dx1, dy1, dx2, dy2, sx1, sy1,
                                    sx2, sy2, bgcolor, observer);
    } catch (InvalidPipeException e) {
        try {
            revalidateAll();
            return imagepipe.scaleImage(this, img, dx1, dy1, dx2, dy2, sx1,
                                        sy1, sx2, sy2, bgcolor, 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
Project: jdk8u-jdk   File: MultiResolutionImageTest.java   View Source Code Vote up 4 votes
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 17
Project: jdk8u-jdk   File: WDragSourceContextPeer.java   View Source Code Vote up 4 votes
protected void startDrag(Transferable trans,
                         long[] formats, Map 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 18
Project: jdk8u-jdk   File: ImageCache.java   View Source Code Vote up 4 votes
/**
 * 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 19
Project: hearthstone   File: Img.java   View Source Code Vote up 4 votes
private static int[] getPixels(Image img) throws InterruptedException {
    int[] pix = new int[img.getWidth(null) * img.getHeight(null)];
    PixelGrabber pg = new PixelGrabber(img, 0, 0, img.getWidth(null), img.getHeight(null), pix, 0, img.getWidth(null));
    pg.grabPixels();
    return pix;
}
 
Example 20
Project: parabuild-ci   File: StandardXYItemRenderer.java   View Source Code Vote up 3 votes
/**
 * Returns the hotspot of the image used to draw a single data item.
 * The hotspot is the point relative to the top left of the image
 * that should indicate the data item. The default is the center of the
 * image.
 *
 * @param plot  the plot (can be used to obtain standard color information etc).
 * @param image  the image (can be used to get size information about the image)
 * @param series  the series index
 * @param item  the item index
 * @param x  the x value of the item
 * @param y  the y value of the item
 *
 * @return The hotspot used to draw the data item.
 */
protected Point getImageHotspot(Plot plot, int series, int item,
                                double x, double y, Image image) {

    int height = image.getHeight(null);
    int width = image.getWidth(null);
    return new Point(width / 2, height / 2);

}