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

The following are Jave code examples for showing how to use getWidth() 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: incubator-netbeans   File: Utilities.java   View Source Code Vote up 7 votes
public static Cursor createCustomCursor(Component component, Image icon, String name) {
    Toolkit t = component.getToolkit();
    Dimension d = t.getBestCursorSize(16, 16);
    Image i = icon;

    if (d.width != icon.getWidth(null)) {
        if (((d.width) == 0) && (d.height == 0)) {
            // system doesn't support custom cursors, falling back
            return Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
        }

        // need to resize the icon
        Image empty = ImageUtilities.createBufferedImage(d.width, d.height);
        i = ImageUtilities.mergeImages(icon, empty, 0, 0);
    }

    return t.createCustomCursor(i, new Point(1, 1), name);
}
 
Example 2
Project: VASSAL-src   File: DataArchive.java   View Source Code Vote up 6 votes
/**
 * Get the size of an image without loading and decoding it.
 *
 * @param name filename of the image
 * @return the size of the image
 * @deprecated Use {@link ImageUtils.getImageSize} or
 *    {@link SVGImageUtils.getImageSize} instead.
 */
@Deprecated
public Dimension getImageSize(String name) throws IOException {
  final ImageSource src;

  if (name.startsWith("/")) {
    if (name.toLowerCase().endsWith(".svg"))
      return SVGImageUtils.getImageSize(name, getImageInputStream(name));
    else
      return ImageUtils.getImageSize(name, getImageInputStream(name));
  }
  else if ((src = imageSources.get(name)) != null) {
    final Image image = src.getImage();
    return image != null ?
      new Dimension(image.getWidth(null), image.getHeight(null)) :
      new Dimension();
  }
  else if (name.toLowerCase().endsWith(".svg")) {
    return SVGImageUtils.getImageSize(name, getImageInputStream(name));
  }
  else {
    return ImageUtils.getImageSize(name, getImageInputStream(name));
  }
}
 
Example 3
Project: OpenJSharp   File: PathGraphics.java   View Source Code Vote up 6 votes
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 4
Project: freecol   File: TerrainDetailPanel.java   View Source Code Vote up 6 votes
/**
 * {@inheritDoc}
 */
@Override
public void addSubTrees(DefaultMutableTreeNode root) {
    DefaultMutableTreeNode node
        = new DefaultMutableTreeNode(new ColopediaTreeItem(this, getId(),
                                     getName(), null));
    for (TileType t : getSpecification().getTileTypeList()) {
        Image tile = SwingGUI.createTileImageWithOverlayAndForest(t,
            new Dimension(-1, ImageLibrary.ICON_SIZE.height));
        BufferedImage image = new BufferedImage(tile.getWidth(null),
            ImageLibrary.ICON_SIZE.height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();
        g.drawImage(tile, 0, (ImageLibrary.ICON_SIZE.height - tile.getHeight(null)) / 2, null);
        g.dispose();
        ImageIcon icon = new ImageIcon(image);
        node.add(buildItem(t, icon));
    }
    root.add(node);
}
 
Example 5
Project: OpenJSharp   File: RuntimeBuiltinLeafInfoImpl.java   View Source Code Vote up 6 votes
private BufferedImage convertToBufferedImage(Image image) throws IOException {
    if (image instanceof BufferedImage) {
        return (BufferedImage)image;

    } else {
        MediaTracker tracker = new MediaTracker(new Component(){}); // not sure if this is the right thing to do.
        tracker.addImage(image, 0);
        try {
            tracker.waitForAll();
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage());
        }
        BufferedImage bufImage = new BufferedImage(
                image.getWidth(null),
                image.getHeight(null),
                BufferedImage.TYPE_INT_ARGB);

        Graphics g = bufImage.createGraphics();
        g.drawImage(image, 0, 0, null);
        return bufImage;
    }
}
 
Example 6
Project: springboot-training   File: ImageUtil.java   View Source Code Vote up 6 votes
private Image getResizedImage(Image image, int newSize, int operation) {
	int iWidth = image.getWidth(null);
	int iHeight = image.getHeight(null);
	int hints = Image.SCALE_SMOOTH;
	switch (operation) {
	case 1:// 按宽度缩放
		return image.getScaledInstance(newSize, (newSize * iHeight) / iWidth, hints);
	case 2:// 按高度缩放
		return image.getScaledInstance((newSize * iWidth) / iHeight, newSize, hints);
	default:// 哪边大按哪边缩放
		if (iWidth > iHeight) {
			return image.getScaledInstance(newSize, (newSize * iHeight) / iWidth, hints);
		} else {
			return image.getScaledInstance((newSize * iWidth) / iHeight, newSize, hints);
		}
	}
}
 
Example 7
Project: cuttlefish   File: VertexImageShaperDemo.java   View Source Code Vote up 5 votes
public Shape getShape(Vertex v) {
	Icon icon = (Icon) iconMap.get(v);

	if (icon != null && icon instanceof ImageIcon) {

		Image image = ((ImageIcon) icon).getImage();

		Shape shape = (Shape) shapeMap.get(image);
		if (shape == null) {
			if (shapeImages) {
				shape = FourPassImageShaper.getShape(image, 30);
			} else {
				shape = new Rectangle2D.Float(0, 0, 
						image.getWidth(null), image.getHeight(null));
			}
                  if(shape.getBounds().getWidth() > 0 && 
                          shape.getBounds().getHeight() > 0) {
                      int width = image.getWidth(null);
                      int height = image.getHeight(null);
                      AffineTransform transform = 
                          AffineTransform.getTranslateInstance(-width / 2, -height / 2);
                      shape = transform.createTransformedShape(shape);
                      shapeMap.put(image, shape);
                  }
		}
		return shape;
	} else {
		return delegate.getShape(v);
	}
}
 
Example 8
Project: hearthstone   File: Img.java   View Source Code Vote up 5 votes
/**
 * Retorna a cor do pixel da imagem na coordenada passada por parâmetro
 *
 * @param img imagem
 * @param x coordenada X
 * @param y coordenada Y
 * @return Color
 */
public static Color getColor(Image img, int x, int y) {
    try {
        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();
        int index = y * img.getWidth(null) + x;
        Color color = new Color(pix[index], true);
        return color;
    } catch (Exception ex) {
        return new Color(0);
    }
}
 
Example 9
Project: Fetax-AI   File: CodeUtil.java   View Source Code Vote up 5 votes
private static void insertImage(BufferedImage source, String imgPath,
        boolean needCompress) throws Exception {
    File file = new File(imgPath);
    if (!file.exists()) {
        System.err.println(""+imgPath+"   该文件不存在!");
        return;
    }
    Image src = ImageIO.read(new File(imgPath));
    int width = src.getWidth(null);
    int height = src.getHeight(null);
    if (needCompress) {// 压缩LOGO
        if (width > WIDTH) {
            width = WIDTH;
        }
        if (height > HEIGHT) {
            height = HEIGHT;
        }
        Image image = src.getScaledInstance(width, height,
                Image.SCALE_SMOOTH);
        BufferedImage tag = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        g.drawImage(image, 0, 0, null); // 绘制缩小后的图
        g.dispose();
        src = image;
    }
 // 插入LOGO
    Graphics2D graph = source.createGraphics();
    int x = (QRCODE_SIZE - width) / 2;
    int y = (QRCODE_SIZE - height) / 2;
    graph.drawImage(src, x, y, width, height, null);
    Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
    graph.setStroke(new BasicStroke(3f));
    graph.draw(shape);
    graph.dispose();
}
 
Example 10
Project: jdk8u-jdk   File: TranslucentWindowPainter.java   View Source Code Vote up 5 votes
@Override
protected boolean update(Image bb) {
    if (bb instanceof DestSurfaceProvider) {
        Surface s = ((DestSurfaceProvider)bb).getDestSurface();
        if (s instanceof AccelSurface) {
            final int w = bb.getWidth(null);
            final int h = bb.getHeight(null);
            final boolean arr[] = { false };
            final AccelSurface as = (AccelSurface)s;
            RenderQueue rq = as.getContext().getRenderQueue();
            rq.lock();
            try {
                BufferedContext.validateContext(as);
                rq.flushAndInvokeNow(new Runnable() {
                    @Override
                    public void run() {
                        long psdops = as.getNativeOps();
                        arr[0] = updateWindowAccel(psdops, w, h);
                    }
                });
            } catch (InvalidPipeException e) {
                // ignore, false will be returned
            } finally {
                rq.unlock();
            }
            return arr[0];
        }
    }
    return super.update(bb);
}
 
Example 11
Project: OpenJSharp   File: TranslucentWindowPainter.java   View Source Code Vote up 5 votes
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 12
Project: OpenJSharp   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 13
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 14
Project: openjdk-jdk10   File: SunGraphics2D.java   View Source Code Vote up 4 votes
/**
 * 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);
    Boolean hidpiImageDrawn = drawHiDPIImage(img, x, y, x + width, y + height,
                                             0, 0, imgW, imgH, bg, observer,
                                             null);
    if (hidpiImageDrawn != null) {
        return hidpiImageDrawn;
    }

    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 15
Project: Tarski   File: mxGraphicsCanvas2D.java   View Source Code Vote up 4 votes
/**
 * Returns the size for the given image.
 */
protected Dimension getImageSize(Image image) {
  return new Dimension(image.getWidth(null), image.getHeight(null));
}
 
Example 16
Project: openjdk-jdk10   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: SunGraphics2D.java   View Source Code Vote up 4 votes
/**
 * 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 18
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 19
Project: jdk8u-jdk   File: SunGraphics2D.java   View Source Code Vote up 4 votes
/**
 * 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 20
Project: FreeCol   File: FreeColImageBorder.java   View Source Code Vote up 2 votes
/**
 * Get the width of an image. If image is null, return 0.
 * @param im The image.
 * @return The width of the image.
 */
private static int getWidth(Image im) {
    return (im == null) ? 0 : im.getWidth(null);
}