Example usage for java.awt Image getHeight

List of usage examples for java.awt Image getHeight

Introduction

In this page you can find the example usage for java.awt Image getHeight.

Prototype

public abstract int getHeight(ImageObserver observer);

Source Link

Document

Determines the height of the image.

Usage

From source file:net.rptools.maptool.client.ui.ExportDialog.java

/**
 * Finds the extents of the map, sets up zone to be captured. If the user is
 * the GM, the extents include every object and everything that has any
 * area, such as 'fog' and 'visibility' objects.
 * <p>/* ww w  .ja va2s  .c om*/
 * If a background tiling texture is used, the image is aligned to it, so
 * that it can be used on re-import as a new base map image.
 * <p>
 * If the user is a player (or GM posing as a player), the extents only go
 * as far as the revealed fog-of-war.
 * <p>
 * Must be followed by postScreenshot at some point, or the Zone will be
 * messed up.
 * 
 * @return the image to be saved
 */
private PlayerView preScreenshot() throws Exception, OutOfMemoryError {
    assert (!waitingForPostScreenshot) : "preScreenshot() called twice in a row!";

    setupZoneLayers();
    boolean viewAsPlayer = ExportRadioButtons.VIEW_PLAYER.isChecked();

    // First, figure out the 'extents' of the canvas
    //   This will be later modified by the fog (for players),
    //   and by the tiling texture (for re-importing)
    //
    PlayerView view = new PlayerView(viewAsPlayer ? Player.Role.PLAYER : Player.Role.GM);
    Rectangle extents = renderer.zoneExtents(view);
    try {
        // Clip to what the players know about (if applicable).
        // This keeps the player from exporting the map to learn which
        // direction has more 'stuff' in it.
        if (viewAsPlayer) {
            Rectangle fogE = renderer.fogExtents();
            // MapTool.showError(fogE.x + " " + fogE.y + " " + fogE.width + " " + fogE.height);
            if ((fogE.width < 0) || (fogE.height < 0)) {
                MapTool.showError(I18N.getString("dialog.screenshot.error.negativeFogExtents")); // Image is not clipped to show only fog-revealed areas!"));
            } else {
                extents = extents.intersection(fogE);
            }
        }
    } catch (Exception ex) {
        throw (new Exception(I18N.getString("dialog.screenshot.error.noArea"), ex));
    }
    if ((extents == null) || (extents.width == 0) || (extents.height == 0)) {
        throw (new Exception(I18N.getString("dialog.screenshot.error.noArea")));
    }

    // If output includes the tiling 'board' texture, move the upper-left corner
    // to an integer multiple of the background tile (so it matches up on import).
    // We don't need to move the lower-right corner because it doesn't matter for
    // aligning on importing.

    boolean drawBoard = ExportLayers.LAYER_BOARD.isChecked();
    if (drawBoard) {
        DrawablePaint paint = renderer.getZone().getBackgroundPaint();
        DrawableTexturePaint dummy = new DrawableTexturePaint();
        Integer tileX = 0, tileY = 0;

        if (paint.getClass() == dummy.getClass()) {
            Image bgTexture = ImageManager.getImage(((DrawableTexturePaint) paint).getAsset().getId());
            tileX = bgTexture.getWidth(null);
            tileY = bgTexture.getHeight(null);
            Integer x = ((int) Math.floor((float) extents.x / tileX)) * tileX;
            Integer y = ((int) Math.floor((float) extents.y / tileY)) * tileY;
            extents.width = extents.width + (extents.x - x);
            extents.height = extents.height + (extents.y - y);
            extents.x = x;
            extents.y = y;
        }
    }

    // Save the original state of the renderer to restore later.
    // Create a place to put the image, and
    // set up the renderer to encompass the whole extents of the map.

    origBounds = renderer.getBounds();
    origScale = renderer.getZoneScale();

    // Setup the renderer to use the new extents
    Scale s = new Scale();
    s.setOffset(-extents.x, -extents.y);
    renderer.setZoneScale(s);
    renderer.setBounds(extents);

    waitingForPostScreenshot = true;
    return view;
}

From source file:AppSpringLayout.java

private BufferedImage toBufferedImage(Image imageToGetBuffered) {

    if (imageToGetBuffered instanceof BufferedImage) {
        return (BufferedImage) imageToGetBuffered;
    }/*from ww w .j a  v  a 2 s.  c  o m*/

    // Create a buffered image with transparency
    BufferedImage bimage = new BufferedImage(imageToGetBuffered.getWidth(null),
            imageToGetBuffered.getHeight(null), BufferedImage.TYPE_INT_ARGB);

    return bimage;
}

From source file:com.t3.client.ui.ExportDialog.java

/**
 * Finds the extents of the map, sets up zone to be captured. If the user is
 * the GM, the extents include every object and everything that has any
 * area, such as 'fog' and 'visibility' objects.
 * <p>//ww  w .  j av a  2s  .com
 * If a background tiling texture is used, the image is aligned to it, so
 * that it can be used on re-import as a new base map image.
 * <p>
 * If the user is a player (or GM posing as a player), the extents only go
 * as far as the revealed fog-of-war.
 * <p>
 * Must be followed by postScreenshot at some point, or the Zone will be
 * messed up.
 * 
 * @return the image to be saved
 */
private PlayerView preScreenshot() throws Exception, OutOfMemoryError {
    assert (!waitingForPostScreenshot) : "preScreenshot() called twice in a row!";

    setupZoneLayers();
    boolean viewAsPlayer = ExportRadioButtons.VIEW_PLAYER.isChecked();

    // First, figure out the 'extents' of the canvas
    //   This will be later modified by the fog (for players),
    //   and by the tiling texture (for re-importing)
    //
    PlayerView view = new PlayerView(viewAsPlayer ? Player.Role.PLAYER : Player.Role.GM);
    Rectangle extents = renderer.zoneExtents(view);
    try {
        // Clip to what the players know about (if applicable).
        // This keeps the player from exporting the map to learn which
        // direction has more 'stuff' in it.
        if (viewAsPlayer) {
            Rectangle fogE = renderer.fogExtents();
            // TabletopTool.showError(fogE.x + " " + fogE.y + " " + fogE.width + " " + fogE.height);
            if ((fogE.width < 0) || (fogE.height < 0)) {
                TabletopTool.showError(I18N.getString("dialog.screenshot.error.negativeFogExtents")); // Image is not clipped to show only fog-revealed areas!"));
            } else {
                extents = extents.intersection(fogE);
            }
        }
    } catch (Exception ex) {
        throw (new Exception(I18N.getString("dialog.screenshot.error.noArea"), ex));
    }
    if ((extents == null) || (extents.width == 0) || (extents.height == 0)) {
        throw (new Exception(I18N.getString("dialog.screenshot.error.noArea")));
    }

    // If output includes the tiling 'board' texture, move the upper-left corner
    // to an integer multiple of the background tile (so it matches up on import).
    // We don't need to move the lower-right corner because it doesn't matter for
    // aligning on importing.

    boolean drawBoard = ExportLayers.LAYER_BOARD.isChecked();
    if (drawBoard) {
        DrawablePaint paint = renderer.getZone().getBackgroundPaint();
        DrawableTexturePaint dummy = new DrawableTexturePaint();
        Integer tileX = 0, tileY = 0;

        if (paint.getClass() == dummy.getClass()) {
            Image bgTexture = ImageManager.getImage(((DrawableTexturePaint) paint).getAsset().getId());
            tileX = bgTexture.getWidth(null);
            tileY = bgTexture.getHeight(null);
            Integer x = ((int) Math.floor((float) extents.x / tileX)) * tileX;
            Integer y = ((int) Math.floor((float) extents.y / tileY)) * tileY;
            extents.width = extents.width + (extents.x - x);
            extents.height = extents.height + (extents.y - y);
            extents.x = x;
            extents.y = y;
        }
    }

    // Save the original state of the renderer to restore later.
    // Create a place to put the image, and
    // set up the renderer to encompass the whole extents of the map.

    origBounds = renderer.getBounds();
    origScale = renderer.getZoneScale();

    // Setup the renderer to use the new extents
    Scale s = new Scale();
    s.setOffset(-extents.x, -extents.y);
    renderer.setZoneScale(s);
    renderer.setBounds(extents);

    waitingForPostScreenshot = true;
    return view;
}

From source file:processing.app.Theme.java

/**
 * Return an Image object from inside the Processing lib folder.
 *//*  w  w w  .  j a  v a  2 s .co  m*/
static public Image getLibImage(String filename, Component who, int width, int height) {
    Image image = null;

    // Use vector image when available
    Resource vectorFile = getThemeResource(filename + ".svg");
    if (vectorFile.exists()) {
        try {
            image = imageFromSVG(vectorFile.getUrl(), width, height);
        } catch (Exception e) {
            System.err.println("Failed to load " + vectorFile + ": " + e.getMessage());
        }
    }

    Resource bitmapFile = getThemeResource(filename + ".png");

    // Otherwise fall-back to PNG bitmaps, allowing user-defined bitmaps to
    // override built-in svgs
    if (image == null || bitmapFile.getPriority() > vectorFile.getPriority()) {
        Resource bitmap2xFile = getThemeResource(filename + "@2x.png");

        Resource imageFile;
        if (((getScale() > 125 && bitmap2xFile.exists()) || !bitmapFile.exists())
                && (bitmapFile.isUserDefined() && bitmap2xFile.isUserDefined())) {
            imageFile = bitmap2xFile;
        } else {
            imageFile = bitmapFile;
        }
        Toolkit tk = Toolkit.getDefaultToolkit();
        image = tk.getImage(imageFile.getUrl());
    }

    MediaTracker tracker = new MediaTracker(who);
    try {
        tracker.addImage(image, 0);
        tracker.waitForAll();
    } catch (InterruptedException e) {
    }

    if (image.getWidth(null) != width || image.getHeight(null) != height) {
        image = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        try {
            tracker.addImage(image, 1);
            tracker.waitForAll();
        } catch (InterruptedException e) {
        }
    }

    return image;
}

From source file:org.mili.core.graphics.GraphicsUtilTest.java

@Test
@Ignore/*from  w  w  w . j a  v a 2  s. com*/
public void test_Image_scaleImage_Image_int_int() {
    // negativ
    try {
        GraphicsUtil.scaleImage(null, 0, 0);
        fail("here was null given, but method works !");
    } catch (IllegalArgumentException e) {
        assertTrue(true);
    }
    try {
        Image i = GraphicsUtil.readImage(new File(this.dir, "test.jpg"));
        GraphicsUtil.scaleImage(i, -1, 10);
        fail("here was < 0 given, but method works !");
    } catch (IllegalArgumentException e) {
        assertTrue(true);
    } catch (IOException e) {
        e.printStackTrace();
        fail();
    }
    try {
        Image i = GraphicsUtil.readImage(new File(this.dir, "test.jpg"));
        GraphicsUtil.scaleImage(i, 10, -1);
        fail("here was < 0 given, but method works !");
    } catch (IllegalArgumentException e) {
        assertTrue(true);
    } catch (IOException e) {
        e.printStackTrace();
        fail();
    }
    // positiv keine skalierung
    try {
        Image i = GraphicsUtil.readImage(new File(this.dir, "test.jpg"));
        int x = i.getWidth(null);
        int y = i.getHeight(null);
        i = GraphicsUtil.scaleImage(i, 0, 0);
        assertEquals(x, i.getWidth(null));
        assertEquals(y, i.getHeight(null));
    } catch (Exception e) {
        e.printStackTrace();
        fail();
    }
    // positiv skalierung
    try {
        Image i = GraphicsUtil.readImage(new File(this.dir, "test_big.jpg"));
        Image p = GraphicsUtil.readImage(new File(this.dir, "block.jpg"));
        double fx = GraphicsUtil.getRelationFactor(i.getWidth(null), i.getHeight(null), p);
        p = GraphicsUtil.scaleImage(p, (int) fx, (int) fx);
        i = GraphicsUtil.pointCenterImage(i, p, 50, 50);
        i = GraphicsUtil.scaleImage(i, 150, 150);
        GraphicsUtil.writeImage(new File(this.dir, "test_scaled.jpg"), i);
        assertEquals(150, i.getWidth(null));
        assertEquals(150, i.getHeight(null));
    } catch (Exception e) {
        e.printStackTrace();
        fail();
    }
}

From source file:net.frontlinesms.plugins.forms.FormsPluginController.java

private void convertByteImageToFile(byte[] imageByte, String path) throws Exception {
    System.out.println("path ...... convertByteImageToFile ......... " + path);

    ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
    Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg");

    ImageReader reader = (ImageReader) readers.next();
    Object source = bis;//from w w  w .j  ava  2 s  .c  o  m
    ImageInputStream iis = ImageIO.createImageInputStream(source);
    reader.setInput(iis, true);
    ImageReadParam param = reader.getDefaultReadParam();

    Image image = reader.read(0, param);
    //got an image file

    BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null),
            BufferedImage.TYPE_INT_RGB);
    //bufferedImage is the RenderedImage to be written

    Graphics2D g2 = bufferedImage.createGraphics();
    g2.drawImage(image, null, null);

    File imageFile = new File(path);
    ImageIO.write(bufferedImage, "jpg", imageFile);
    System.out.println(" end write image ");
}

From source file:net.sradonia.gui.SplashScreen.java

/**
 * Creates a new splash screen./*from   ww w .  j a  va 2 s .c  o  m*/
 * 
 * @param image
 *            the image to display
 * @param title
 *            the title of the window
 */
public SplashScreen(Image image, String title) {
    log.debug("initializing splash screen");

    if (image == null)
        throw new IllegalArgumentException("null image");

    // create the frame
    window = new JFrame(title) {
        private static final long serialVersionUID = 2193620921531262633L;

        @Override
        public void paint(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            g2d.drawImage(splash, 0, 0, this);
        }
    };
    window.setUndecorated(true);

    // wait for the image to load
    MediaTracker mt = new MediaTracker(window);
    mt.addImage(image, 0);
    try {
        mt.waitForID(0);
    } catch (InterruptedException e1) {
        log.debug("interrupted while waiting for image loading");
    }

    // check for loading errors
    if (mt.isErrorID(0))
        throw new IllegalArgumentException("couldn't load the image");
    if (image.getHeight(null) <= 0 || image.getWidth(null) <= 0)
        throw new IllegalArgumentException("illegal image size");

    setImage(image);

    window.addWindowFocusListener(new WindowFocusListener() {
        public void windowGainedFocus(WindowEvent e) {
            updateSplash();
        }

        public void windowLostFocus(WindowEvent e) {
        }
    });

    timer = new SimpleTimer(new Runnable() {
        public void run() {
            log.debug(timer.getDelay() + "ms timeout reached");
            timer.setRunning(false);
            setVisible(false);
        }
    }, 5000, false);
    timeoutActive = false;
}

From source file:com.t3.client.TabletopTool.java

/**
 * If we're running on OSX we should call this method to download and
 * install the TabletopTool logo from the main web site. We cache this image so
 * that it appears correctly if the application is later executed in
 * "offline" mode, so to speak.//  w  w  w.j a v  a 2s  .c  o m
 */
private static void macOSXicon() {
    // If we're running on OSX, add the dock icon image
    // -- and change our application name to just "TabletopTool" (not currently)
    // We wait until after we call initialize() so that the asset and image managers
    // are configured.
    Image img = null;
    File logoFile = new File(AppUtil.getAppHome("config"), "tabletoptool-dock-icon.png");
    URL logoURL = null;
    try {
        logoURL = new URL("http://services.tabletoptool.com/logo_large.png");
    } catch (MalformedURLException e) {
        showError("Attemping to form URL -- shouldn't happen as URL is hard-coded", e);
    }
    try {
        img = ImageUtil.bytesToImage(FileUtils.readFileToByteArray(logoFile));
    } catch (IOException e) {
        log.debug("Attemping to read cached icon: " + logoFile, e);
        try {
            img = ImageUtil.bytesToImage(FileUtil.getBytes(logoURL));
            // If we did download the logo, save it to the 'config' dir for later use.
            BufferedImage bimg = ImageUtil.createCompatibleImage(img, img.getWidth(null), img.getHeight(null),
                    null);
            FileUtils.writeByteArrayToFile(logoFile, ImageUtil.imageToBytes(bimg, "png"));
            img = bimg;
        } catch (IOException e1) {
            log.warn("Cannot read '" + logoURL + "' or  cached '" + logoFile + "'; no dock icon", e1);
        }
    }
    /*
     * Unfortunately the next line doesn't allow Eclipse to compile the code
     * on anything but a Mac. Too bad because there's no problem at runtime
     * since this code wouldn't be executed an any machine *except* a Mac.
     * Sigh.
     * 
     * com.apple.eawt.Application appl =
     * com.apple.eawt.Application.getApplication();
     */
    try {
        Class<?> appClass = Class.forName("com.apple.eawt.Application");
        Method getApplication = appClass.getDeclaredMethod("getApplication", (Class[]) null);
        Object appl = getApplication.invoke(null, (Object[]) null);
        Method setDockIconImage = appl.getClass().getDeclaredMethod("setDockIconImage",
                new Class[] { java.awt.Image.class });
        // If we couldn't grab the image for some reason, don't set the dock bar icon!  Duh!
        if (img != null)
            setDockIconImage.invoke(appl, new Object[] { img });

        if (T3Util.isDebugEnabled()) {
            // For some reason Mac users don't like the dock badge icon.  But from a development standpoint I like seeing the
            // version number in the dock bar.  So we'll only include it when running with T3_DEV on the command line.
            Method setDockIconBadge = appl.getClass().getDeclaredMethod("setDockIconBadge",
                    new Class[] { java.lang.String.class });
            String vers = getVersion();
            vers = vers.substring(vers.length() - 2);
            vers = vers.replaceAll("[^0-9]", "0"); // Convert all non-digits to zeroes
            setDockIconBadge.invoke(appl, new Object[] { vers });
        }
    } catch (Exception e) {
        log.info(
                "Cannot find/invoke methods on com.apple.eawt.Application; use -X command line options to set dock bar attributes",
                e);
    }
}

From source file:ucar.unidata.idv.control.chart.ChartManager.java

/**
 * actually update the thumbnail image//w  ww.  jav  a 2s  . c  o  m
 */
public void updateThumbInner() {
    try {
        if (!showThumb) {
            return;
        }
        //            if (settingData) return;
        if ((getContents().getWidth() == 0) || (getContents().getHeight() == 0)) {
            //                Misc.runInABit(1000, this, "updateThumb",null);
            return;
        }
        List images = new ArrayList();
        Image thumb = ImageUtils.getImage(getContents());
        if (thumb == null) {
            return;
        }
        if ((thumb.getWidth(null) <= 0) || (thumb.getHeight(null) <= 0)) {
            return;
        }
        double ratio = thumb.getWidth(null) / (double) thumb.getHeight(null);
        //            int width = Math.max(label.getWidth(),200);
        int width = 200;
        int height = (int) (width / ratio);
        thumb = ImageUtils.toBufferedImage(thumb.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING),
                BufferedImage.TYPE_INT_RGB);
        boolean chartsShowingSomething = false;
        for (ChartHolder chartHolder : chartHolders) {
            if (chartHolder.getBeingShown() && chartHolder.hasParameters()) {
                chartsShowingSomething = true;
                break;
            }
        }
        if (chartsShowingSomething) {
            getThumb().setIcon(new ImageIcon(thumb));
        } else {
            getThumb().setIcon(GuiUtils.getImageIcon("/auxdata/ui/icons/OnePixel.gif"));
        }

    } catch (Exception exc) {
        //            LogUtil.logException("Showing thumbnail", exc);
    }
    thumbUpdatePending = false;
}

From source file:net.pms.medialibrary.commons.helpers.FileImportHelper.java

/**
 * Creates a buffered image from an image
 * @param image the image//  w w  w  . j a  v  a 2  s . c  o  m
 * @return the buffered image
 */
public static BufferedImage getBufferedImage(Image image) {
    if (image instanceof BufferedImage) {
        return (BufferedImage) image;
    }

    // This code ensures that all the pixels in the image are loaded
    image = new ImageIcon(image).getImage();

    // Determine if the image has transparent pixels; for this method's
    // implementation, see Determining If an Image Has Transparent Pixels
    boolean hasAlpha = hasAlpha(image);

    // Create a buffered image with a format that's compatible with the screen
    BufferedImage bimage = null;
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    try {
        // Determine the type of transparency of the new buffered image
        int transparency = Transparency.OPAQUE;
        if (hasAlpha) {
            transparency = Transparency.BITMASK;
        }

        // Create the buffered image
        GraphicsDevice gs = ge.getDefaultScreenDevice();
        GraphicsConfiguration gc = gs.getDefaultConfiguration();
        bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
    } catch (HeadlessException e) {
        // The system does not have a screen
    }

    if (bimage == null) {
        // Create a buffered image using the default color model
        int type = BufferedImage.TYPE_INT_RGB;
        if (hasAlpha) {
            type = BufferedImage.TYPE_INT_ARGB;
        }
        bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
    }

    // Copy image to buffered image
    Graphics g = bimage.createGraphics();

    // Paint the image onto the buffered image
    g.drawImage(image, 0, 0, null);
    g.dispose();

    return bimage;
}