List of usage examples for java.awt Image getWidth
public abstract int getWidth(ImageObserver observer);
From source file:org.mili.core.graphics.GraphicsUtilTest.java
@Test @Ignore/*from w w w .j ava2 s . c om*/ 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:org.lnicholls.galleon.util.Tools.java
public static Image getImage(URL url, int width, int height) { if (url != null) { // System.out.println(url); try {//from w w w . j av a 2 s. c o m Image internetImage = null; if (log.isDebugEnabled()) log.debug("Downloading internet image=" + url.toExternalForm()); class TimedThread implements Callable { private URL mUrl; public TimedThread(URL url) { mUrl = url; } public synchronized java.lang.Object call() throws java.lang.Exception { return new ImageTracker(mUrl).load(); } } TimedCallable timedCallable = new TimedCallable(new TimedThread(url), 2000 * 60); internetImage = (Image) timedCallable.call(); // System.out.println("internetImage="+internetImage); if (internetImage == null) { log.error("Invalid internet image: " + url.getPath()); } else { // System.out.println("width="+width); // System.out.println("height="+height); if (width == -1) width = internetImage.getWidth(null); if (height == -1) height = internetImage.getHeight(null); // System.out.println("width="+width); // System.out.println("height="+height); Image image = null; if (internetImage instanceof BufferedImage) { image = ImageManipulator.getScaledImage((BufferedImage) internetImage, width, height); // System.out.println("image1="+image); } else { try { image = createBufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = ((BufferedImage) image).createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(internetImage, 0, 0, width, height, null); graphics2D.dispose(); graphics2D = null; // System.out.println("image2="+image); } catch (Throwable ex) { // ex.printStackTrace(); image = internetImage.getScaledInstance(width, height, Image.SCALE_SMOOTH); // System.out.println("image3="+image); } } internetImage.flush(); internetImage = null; return image; } } catch (Throwable ex) { // ex.printStackTrace(); Tools.logException(Tools.class, ex, url.toExternalForm()); } } return null; }
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;// w ww . j av a 2 s . c om 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: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 va2 s. 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//from w w w .j a v a 2 s. co 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//from w w w.ja v a 2s. c om * @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; }
From source file:net.sradonia.gui.SplashScreen.java
/** * Creates a new splash screen./*from w w w. j a v a 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:net.rptools.maptool.client.MapTool.java
/** * If we're running on OSX we should call this method to download and * install the MapTool 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./*from ww w.j a v a 2 s .c om*/ */ private static void macOSXicon() { // If we're running on OSX, add the dock icon image // -- and change our application name to just "MapTool" (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"), "maptool-dock-icon.png"); URL logoURL = null; try { logoURL = new URL("http://www.rptools.net/images/logo/RPTools_Map_Logo.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 (MapToolUtil.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 MAPTOOL_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:jatoo.app.App.java
public App(final String title) { this.title = title; ///*from w w w . j a va 2 s . c o m*/ // load properties properties = new AppProperties(new File(getWorkingDirectory(), "app.properties")); properties.loadSilently(); // // resources texts = new ResourcesTexts(getClass(), new ResourcesTexts(App.class)); images = new ResourcesImages(getClass(), new ResourcesImages(App.class)); // // create & initialize the window if (isDialog()) { window = new JDialog((Frame) null, getTitle()); if (isUndecorated()) { ((JDialog) window).setUndecorated(true); ((JDialog) window).setBackground(new Color(0, 0, 0, 0)); } ((JDialog) window).setResizable(isResizable()); } else { window = new JFrame(getTitle()); if (isUndecorated()) { ((JFrame) window).setUndecorated(true); ((JFrame) window).setBackground(new Color(0, 0, 0, 0)); } ((JFrame) window).setResizable(isResizable()); } window.addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent e) { System.exit(0); } @Override public void windowIconified(final WindowEvent e) { if (isHideWhenMinimized()) { hide(); } } }); // // set icon images // is either all icons from initializer package // or all icons from app package List<Image> windowIconImages = new ArrayList<>(); String[] windowIconImagesNames = new String[] { "016", "020", "022", "024", "032", "048", "064", "128", "256", "512" }; for (String size : windowIconImagesNames) { try { windowIconImages.add(new ImageIcon(getClass().getResource("app-icon-" + size + ".png")).getImage()); } catch (Exception e) { } } if (windowIconImages.size() == 0) { for (String size : windowIconImagesNames) { try { windowIconImages .add(new ImageIcon(App.class.getResource("app-icon-" + size + ".png")).getImage()); } catch (Exception e) { } } } window.setIconImages(windowIconImages); // // this is the place for to call init method // after all local components are created // from now (after init) is only configuration init(); // // set content pane ( and ansure transparency ) JComponent contentPane = getContentPane(); contentPane.setOpaque(false); ((RootPaneContainer) window).setContentPane(contentPane); // // pack the window right after the set of the content pane window.pack(); // // center window (as default in case restore fails) // and try to restore the last location window.setLocationRelativeTo(null); window.setLocation(properties.getLocation(window.getLocation())); if (!isUndecorated()) { if (properties.getLastUndecorated(isUndecorated()) == isUndecorated()) { if (isResizable() && isSizePersistent()) { final String currentLookAndFeel = String.valueOf(UIManager.getLookAndFeel()); if (properties.getLastLookAndFeel(currentLookAndFeel).equals(currentLookAndFeel)) { window.setSize(properties.getSize(window.getSize())); } } } } // // fix location if out of screen Rectangle intersection = window.getGraphicsConfiguration().getBounds().intersection(window.getBounds()); if ((intersection.width < window.getWidth() * 1 / 2) || (intersection.height < window.getHeight() * 1 / 2)) { UIUtils.setWindowLocationRelativeToScreen(window); } // // restore some properties setAlwaysOnTop(properties.isAlwaysOnTop()); setHideWhenMinimized(properties.isHideWhenMinimized()); setTransparency(properties.getTransparency(transparency)); // // null is also a good value for margins glue gaps (is [0,0,0,0]) Insets marginsGlueGaps = getMarginsGlueGaps(); if (marginsGlueGaps == null) { marginsGlueGaps = new Insets(0, 0, 0, 0); } // // glue to margins on Ctrl + ARROWS if (isGlueToMarginsOnCtrlArrows()) { UIUtils.setActionForCtrlDownKeyStroke(((RootPaneContainer) window).getRootPane(), new ActionGlueMarginBottom(window, marginsGlueGaps.bottom)); UIUtils.setActionForCtrlLeftKeyStroke(((RootPaneContainer) window).getRootPane(), new ActionGlueMarginLeft(window, marginsGlueGaps.left)); UIUtils.setActionForCtrlRightKeyStroke(((RootPaneContainer) window).getRootPane(), new ActionGlueMarginRight(window, marginsGlueGaps.right)); UIUtils.setActionForCtrlUpKeyStroke(((RootPaneContainer) window).getRootPane(), new ActionGlueMarginTop(window, marginsGlueGaps.top)); } // // drag to move ( when provided component is not null ) JComponent dragToMoveComponent = getDragToMoveComponent(); if (dragToMoveComponent != null) { // // move the window by dragging the UI component int marginsGlueRange = Math.min(window.getGraphicsConfiguration().getBounds().width, window.getGraphicsConfiguration().getBounds().height); marginsGlueRange /= 60; marginsGlueRange = Math.max(marginsGlueRange, 15); UIUtils.forwardDragAsMove(dragToMoveComponent, window, marginsGlueRange, marginsGlueGaps); // // window popup dragToMoveComponent.addMouseListener(new MouseAdapter() { public void mouseReleased(final MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { windowPopup = getWindowPopup(e.getLocationOnScreen()); windowPopup.setVisible(true); } } }); // // always dispose the popup when window lose the focus window.addFocusListener(new FocusAdapter() { public void focusLost(final FocusEvent e) { if (windowPopup != null) { windowPopup.setVisible(false); windowPopup = null; } } }); } // // tray icon if (hasTrayIcon()) { if (SystemTray.isSupported()) { Image trayIconImage = windowIconImages.get(0); Dimension trayIconSize = SystemTray.getSystemTray().getTrayIconSize(); for (Image windowIconImage : windowIconImages) { if (Math.abs(trayIconSize.width - windowIconImage.getWidth(null)) < Math .abs(trayIconImage.getWidth(null) - windowIconImage.getWidth(null))) { trayIconImage = windowIconImage; } } final TrayIcon trayIcon = new TrayIcon(trayIconImage); trayIcon.setPopupMenu(getTrayIconPopup()); trayIcon.addMouseListener(new MouseAdapter() { public void mouseClicked(final MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e)) { if (e.getClickCount() >= 2) { if (window.isVisible()) { hide(); } else { show(); } } } } }); try { SystemTray.getSystemTray().add(trayIcon); } catch (AWTException e) { logger.error( "unexpected exception trying to add the tray icon ( the desktop system tray is missing? )", e); } } else { logger.error("the system tray is not supported on the current platform"); } } // // hidden or not if (properties.isVisible()) { window.setVisible(true); } // // close the splash screen // if there is one try { SplashScreen splash = SplashScreen.getSplashScreen(); if (splash != null) { splash.close(); } } catch (UnsupportedOperationException e) { getLogger().info("splash screen not supported", e); } // // add shutdown hook for #destroy() Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { App.this.destroy(); } }); // // after init afterInit(); }
From source file:org.polymap.core.data.image.ImageTransparencyProcessor.java
public static BufferedImage transparency(Image image, final Color markerColor) throws IOException { long start = System.currentTimeMillis(); RGBImageFilter filter = new RGBImageFilter() { // the color we are looking for... Alpha bits are set to opaque public int markerRGB = markerColor.getRGB() | 0xFF000000; byte threshold = 25; double range = ((double) 0xFF) / (3 * threshold); public final int filterRGB(int x, int y, int rgb) { Color probe = new Color(rgb); //log.info( "probe=" + probe + ", marker=" + markerColor ); // delta values int dRed = markerColor.getRed() - probe.getRed(); int dGreen = markerColor.getGreen() - probe.getGreen(); int dBlue = markerColor.getBlue() - probe.getBlue(); //log.info( " dRed=" + dRed + ", dGreen=" + dGreen ); if (dRed >= 0 && dRed < threshold && dGreen >= 0 && dGreen < threshold && dBlue >= 0 && dBlue < threshold) { int alpha = (int) Math.round(range * (dRed + dGreen + dBlue)); //log.info( " -> alpha=" + alpha ); return ((alpha << 24) | 0x00FFFFFF) & rgb; } else { // nothing to do return rgb; }/*ww w . j a va2 s . c o m*/ } }; // BufferedImage bimage = null; // if (image instanceof BufferedImage) { // bimage = (BufferedImage)image; // } // else { // bimage = new BufferedImage( // image.getHeight( null ), image.getWidth( null ), BufferedImage.TYPE_INT_ARGB ); // Graphics g = bimage.getGraphics(); // g.drawImage( image, 0, 0, null ); // g.dispose(); // } ImageProducer ip = new FilteredImageSource(image.getSource(), filter); Image result = Toolkit.getDefaultToolkit().createImage(ip); BufferedImage bresult = new BufferedImage(image.getHeight(null), image.getWidth(null), BufferedImage.TYPE_INT_ARGB); Graphics g = bresult.getGraphics(); g.drawImage(result, 0, 0, null); g.dispose(); // // XXX this can surely be done any more clever // int width = bimage.getWidth(); // int height = bimage.getHeight(); // for (int x=bimage.getMinX(); x<width; x++) { // for (int y=bimage.getMinY(); y<height; y++) { // int filtered = filter.filterRGB( x, y, bimage.getRGB( x, y ) ); // result.setRGB( x, y, filtered ); // } // } log.debug("Transparency done. (" + (System.currentTimeMillis() - start) + "ms)"); return bresult; }