Here are the examples of the java api class java.awt.Image taken from open source projects.
1. LoadingStandardIcons#main()
Project: openjdk
File: LoadingStandardIcons.java
File: LoadingStandardIcons.java
public static void main(final String[] args) { final Object bi; try { bi = Introspector.getBeanInfo(JButton.class); } catch (IntrospectionException e) { throw new RuntimeException(e); } final Image m16 = ((BeanInfo) bi).getIcon(BeanInfo.ICON_MONO_16x16); final Image m32 = ((BeanInfo) bi).getIcon(BeanInfo.ICON_MONO_32x32); final Image c16 = ((BeanInfo) bi).getIcon(BeanInfo.ICON_COLOR_16x16); final Image c32 = ((BeanInfo) bi).getIcon(BeanInfo.ICON_COLOR_32x32); if (m16 == null || m32 == null || c16 == null || c32 == null) { throw new RuntimeException("Image should not be null"); } }
2. ResourceEditorApp#startup()
Project: CodenameOne
File: ResourceEditorApp.java
File: ResourceEditorApp.java
/** * At startup create and show the main frame of the application. */ @Override protected void startup() { ri = new ResourceEditorView(this, fileToLoad); show(ri); Image large = Toolkit.getDefaultToolkit().createImage(getClass().getResource("/application64.png")); Image small = Toolkit.getDefaultToolkit().createImage(getClass().getResource("/application48.png")); try { // setIconImages is only available in JDK 1.6 getMainFrame().setIconImages(Arrays.asList(new Image[] { large, small })); } catch (Throwable err) { getMainFrame().setIconImage(small); } }
3. MultiResolutionImageTest#testToolkitMultiResolutionImageChache()
Project: openjdk
File: MultiResolutionImageTest.java
File: MultiResolutionImageTest.java
static void testToolkitMultiResolutionImageChache(String fileName, URL url) { Image img1 = Toolkit.getDefaultToolkit().getImage(fileName); if (!(img1 instanceof MultiResolutionImage)) { throw new RuntimeException("Not a MultiResolutionImage"); } Image img2 = Toolkit.getDefaultToolkit().getImage(fileName); if (img1 != img2) { throw new RuntimeException("Image is not cached"); } img1 = Toolkit.getDefaultToolkit().getImage(url); if (!(img1 instanceof MultiResolutionImage)) { throw new RuntimeException("Not a MultiResolutionImage"); } img2 = Toolkit.getDefaultToolkit().getImage(url); if (img1 != img2) { throw new RuntimeException("Image is not cached"); } }
4. GeneratorWindow#generateMarker()
Project: droidar
File: GeneratorWindow.java
File: GeneratorWindow.java
private Image generateMarker(int number) { int size = 8; int maxBitLength = 12; int maxIntNumber = 4095; int[][] matrix = genMatrix(Integer.toBinaryString(number), size, maxBitLength); int[] pixels = matrixToLinearList(matrix, size); Image i = createImage(new MemoryImageSource(size, size, pixels, 0, size)); return i.getScaledInstance(200, 200, java.awt.Image.SCALE_DEFAULT); }
5. ImageScaler#scaleImage()
Project: communote-server
File: ImageScaler.java
File: ImageScaler.java
/** * Scale the image and take care of the aspect ratio if {@code sameAspectRatio} is {@code true}. * * @param image * the image to scale * @param newHeight * The new height * @param newWidth * The new width * @param preserveAspectRatio * preserve aspect ratio * @return the scaled imaged */ private BufferedImage scaleImage(BufferedImage image, int newHeight, int newWidth, boolean preserveAspectRatio) { int height = -1; int width = -1; if (preserveAspectRatio) { double fixedRatio = (double) newWidth / (double) newHeight; if ((double) image.getWidth() / (double) image.getHeight() >= fixedRatio) { width = newWidth; } else { height = newHeight; } } else { width = newWidth; height = newHeight; } Image scaledImage = image.getScaledInstance(width, height, Image.SCALE_SMOOTH); return toBufferedImage(scaledImage); }
6. ProjectFrame#initData()
Project: command-manager
File: ProjectFrame.java
File: ProjectFrame.java
private void initData() { this.projectManager = new ProjectManager(); List<Project> projectList = projectManager.getProjects(); //Set window title this.setTitle(ProjectManager.applicationName); //Bound project list combo box with project name this.cbProjectList.removeAllItems(); for (Project p : projectList) { this.cbProjectList.addItem(p.getProjectName()); } //Set the default loaded project. int selectedProjectIndex = 0; for (int i = 0; i < projectList.size(); ++i) { if (projectList.get(i).isSelected()) { selectedProjectIndex = i; break; } } this.cbProjectList.setSelectedIndex(selectedProjectIndex); this.showProject(projectList.get(selectedProjectIndex)); //Set frame icon. Image icon = Toolkit.getDefaultToolkit().getImage(ProjectManager.BASE_DIR + "pic/palette.png"); this.setIconImage(icon); }
7. FileChooserDemo#doFilter()
Project: beautyeye
File: FileChooserDemo.java
File: FileChooserDemo.java
private void doFilter(BufferedImageOp imageOp) { BufferedImage newImage = new BufferedImage(image.getColorModel(), image.getRaster().createCompatibleWritableRaster(image.getWidth(), image.getHeight()), image.isAlphaPremultiplied(), new Hashtable<Object, Object>()); imageOp.filter(image, newImage); image = newImage; lbImage.setIcon(new ImageIcon(image)); setState(State.IMAGE_CHANGED, false); }
8. FileChooserDemo#doAffineTransform()
Project: beautyeye
File: FileChooserDemo.java
File: FileChooserDemo.java
private void doAffineTransform(int width, int height, AffineTransform transform) { BufferedImage newImage = new BufferedImage(image.getColorModel(), image.getRaster().createCompatibleWritableRaster(width, height), image.isAlphaPremultiplied(), new Hashtable<Object, Object>()); ((Graphics2D) newImage.getGraphics()).drawRenderedImage(image, transform); image = newImage; lbImage.setIcon(new ImageIcon(image)); setState(State.IMAGE_CHANGED, false); }
9. MtomSampleMTOMThresholdService#sendImage()
Project: axis2-java
File: MtomSampleMTOMThresholdService.java
File: MtomSampleMTOMThresholdService.java
public ImageDepot sendImage(ImageDepot input) { TestLogger.logger.debug("MtomSampleMTOMEnableService [new sendImage request received]"); DataHandler data = input.getImageData(); TestLogger.logger.debug("[contentType] " + data.getContentType()); ImageDepot output = (new ObjectFactory()).createImageDepot(); Image image = null; resetAttachmentUnmarshallingMonitor(); try { InputStream stream = (InputStream) data.getContent(); image = ImageIO.read(stream); DataSource imageDS = new DataSourceImpl("image/jpeg", "test.jpg", image); DataHandler handler = new DataHandler(imageDS); output.setImageData(handler); } catch (Exception e) { throw new WebServiceException(e); } return output; }
10. StdDraw#picture()
Project: algs4
File: StdDraw.java
File: StdDraw.java
/** * Draws the specified image centered at (<em>x</em>, <em>y</em>), rotated * given number of degrees, and rescaled to the specified bounding box. * 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 scaledWidth the width of the scaled image in pixels * @param scaledHeight the height of the scaled image in pixels * @param degrees is the number of degrees to rotate counterclockwise * @throws IllegalArgumentException if either {@code scaledWidth} * or {@code scaledHeight} is negative * @throws IllegalArgumentException if the image filename is invalid */ public static void picture(double x, double y, String filename, double scaledWidth, double scaledHeight, double degrees) { if (scaledWidth < 0) throw new IllegalArgumentException("width is negative: " + scaledWidth); if (scaledHeight < 0) throw new IllegalArgumentException("height is negative: " + scaledHeight); Image image = getImage(filename); double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(scaledWidth); double hs = factorY(scaledHeight); if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + filename + " is corrupt"); if (ws <= 1 && hs <= 1) pixel(x, y); offscreen.rotate(Math.toRadians(-degrees), xs, ys); offscreen.drawImage(image, (int) Math.round(xs - ws / 2.0), (int) Math.round(ys - hs / 2.0), (int) Math.round(ws), (int) Math.round(hs), null); offscreen.rotate(Math.toRadians(+degrees), xs, ys); draw(); }
11. StdDraw#picture()
Project: algs4
File: StdDraw.java
File: StdDraw.java
/** * Draws the specified image centered at (<em>x</em>, <em>y</em>), * rescaled to the specified bounding box. * 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 scaledWidth the width of the scaled image in pixels * @param scaledHeight the height of the scaled image in pixels * @throws IllegalArgumentException if either {@code scaledWidth} * or {@code scaledHeight} is negative * @throws IllegalArgumentException if the image filename is invalid */ public static void picture(double x, double y, String filename, double scaledWidth, double scaledHeight) { Image image = getImage(filename); if (scaledWidth < 0) throw new IllegalArgumentException("width is negative: " + scaledWidth); if (scaledHeight < 0) throw new IllegalArgumentException("height is negative: " + scaledHeight); double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(scaledWidth); double hs = factorY(scaledHeight); if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + filename + " is corrupt"); if (ws <= 1 && hs <= 1) pixel(x, y); else { offscreen.drawImage(image, (int) Math.round(xs - ws / 2.0), (int) Math.round(ys - hs / 2.0), (int) Math.round(ws), (int) Math.round(hs), null); } draw(); }
12. Draw#picture()
Project: algs4
File: Draw.java
File: Draw.java
/** * Draws picture (gif, jpg, or png) centered on (x, y), rotated * given number of degrees, rescaled to w-by-h. * * @param x the center x-coordinate of the image * @param y the center y-coordinate of the image * @param s the name of the image/picture, e.g., "ball.gif" * @param w the width of the image * @param h the height of the image * @param degrees is the number of degrees to rotate counterclockwise * @throws IllegalArgumentException if the image is corrupt */ public void picture(double x, double y, String s, double w, double h, double degrees) { Image image = getImage(s); double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(w); double hs = factorY(h); if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + s + " is corrupt"); if (ws <= 1 && hs <= 1) pixel(x, y); offscreen.rotate(Math.toRadians(-degrees), xs, ys); offscreen.drawImage(image, (int) Math.round(xs - ws / 2.0), (int) Math.round(ys - hs / 2.0), (int) Math.round(ws), (int) Math.round(hs), null); offscreen.rotate(Math.toRadians(+degrees), xs, ys); draw(); }
13. Draw#picture()
Project: algs4
File: Draw.java
File: Draw.java
/** * Draws picture (gif, jpg, or png) centered on (x, y), rescaled to w-by-h. * * @param x the center x coordinate of the image * @param y the center y coordinate of the image * @param s the name of the image/picture, e.g., "ball.gif" * @param w the width of the image * @param h the height of the image * @throws IllegalArgumentException if the image is corrupt */ public void picture(double x, double y, String s, double w, double h) { Image image = getImage(s); double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(w); double hs = factorY(h); if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + s + " is corrupt"); if (ws <= 1 && hs <= 1) pixel(x, y); else { offscreen.drawImage(image, (int) Math.round(xs - ws / 2.0), (int) Math.round(ys - hs / 2.0), (int) Math.round(ws), (int) Math.round(hs), null); } draw(); }
14. OsXGui#setup()
Project: zaproxy
File: OsXGui.java
File: OsXGui.java
/** * Setups the GUI of ZAP for OSX. * <p> * Sets OS X related GUI properties and functionalities. */ public static void setup() { // Set the various and sundry OS X-specific system properties System.setProperty("apple.laf.useScreenMenuBar", "true"); // Broken and unfixed; thanks, Apple System.setProperty("dock:name", "ZAP"); // more thx System.setProperty("com.apple.mrj.application.apple.menu.about.name", "ZAP"); // Override various handlers, so that About, Preferences, and Quit behave in an OS X typical fashion. LOGGER.info("Initializing OS X specific settings, despite Apple's best efforts"); // Attempt to load the apple classes Application app = Application.getApplication(); // Set the dock image icon Image img = Toolkit.getDefaultToolkit().getImage(GuiBootstrap.class.getResource("/resource/zap1024x1024.png")); app.setDockIconImage(img); // Set handlers for About and Preferences app.setAboutHandler(new OSXAboutHandler()); app.setPreferencesHandler(new OSXPreferencesHandler()); // Let's not forget to clean up our database mess when we Quit OSXQuitHandler quitHandler = new OSXQuitHandler(); // quitHandler.removeZAPViewItem(view); // TODO app.setQuitHandler(quitHandler); }
15. WebcamStaticsTest#test_getImage()
Project: webcam-capture
File: WebcamStaticsTest.java
File: WebcamStaticsTest.java
@Test public void test_getImage() { System.out.println(Thread.currentThread().getName() + ": test_getImage() start"); Webcam webcam = Webcam.getDefault(); webcam.open(); Assert.assertSame(DummyDriver.class, Webcam.getDriver().getClass()); Image image = webcam.getImage(); Assert.assertNotNull(image); System.out.println(Thread.currentThread().getName() + ": test_getImage() end"); }
16. CachedTheme#paint()
Project: tomighty
File: CachedTheme.java
File: CachedTheme.java
@Override public final void paint(Canvas canvas) { Colors colors = look.colors(); Cache cache = caches.of(Images.class); String name = getClass().getSimpleName() + "_" + colors.getClass().getSimpleName(); Image image = cache.get(name); if (image == null) { paint(canvas, look); cache.store(canvas.image(), name); } else { canvas.paint(image); } }
17. ThumbnailatorTest#testCreateThumbnail_III_CorrectUsage()
Project: thumbnailator
File: ThumbnailatorTest.java
File: ThumbnailatorTest.java
/** * Test for * {@link Thumbnailator#createThumbnail(Image, int, int)} * where, * * 1) Method arguments are correct * * Expected outcome is, * * 1) Processing will complete successfully. * */ @Test public void testCreateThumbnail_III_CorrectUsage() { /* * Actual test */ BufferedImage img = new BufferedImageBuilder(200, 200, BufferedImage.TYPE_INT_ARGB).build(); Image thumbnail = Thumbnailator.createThumbnail((Image) img, 50, 50); assertEquals(50, thumbnail.getWidth(null)); assertEquals(50, thumbnail.getHeight(null)); }
18. ImageManager#getExportImage()
Project: SproutLife
File: ImageManager.java
File: ImageManager.java
public BufferedImage getExportImage() { Rectangle2D.Double imageRectangle = getPaddedExportImageSize(); Image logoImage = getLogoImage(imageRectangle.width, imageRectangle.height); BufferedImage image = generateImage((int) imageRectangle.width, (int) imageRectangle.height, logoImage, SAVE_IMAGE_PAD); return image; }
19. ImageBanner#resizeImage()
Project: spring-boot
File: ImageBanner.java
File: ImageBanner.java
private BufferedImage resizeImage(BufferedImage image, int width, int height) { if (width < 1) { width = 1; } if (height <= 0) { double aspectRatio = (double) width / image.getWidth() * 0.5; height = (int) Math.ceil(image.getHeight() * aspectRatio); } BufferedImage resized = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Image scaled = image.getScaledInstance(width, height, Image.SCALE_DEFAULT); resized.getGraphics().drawImage(scaled, 0, 0, null); return resized; }
20. NonOpaqueDestLCDAATest#render()
Project: openjdk
File: NonOpaqueDestLCDAATest.java
File: NonOpaqueDestLCDAATest.java
public void render(Graphics g, int w, int h) { initImages(w, h); g.setColor(new Color(0xAD, 0xD8, 0xE6)); g.fillRect(0, 0, w, h); Graphics2D g2d = (Graphics2D) g.create(); for (Image im : images) { g2d.drawImage(im, 0, 0, null); g2d.translate(0, im.getHeight(null)); } }
21. AddNoLeak#main()
Project: openjdk
File: AddNoLeak.java
File: AddNoLeak.java
public static void main(String[] args) { System.setProperty("java.awt.headless", "true"); Container cont = new Container(); Image img = cont.createImage(new DummyImageSource()); for (int i = 0; i < 15000; i++) { img.getWidth(new ImageObserver() { public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { return false; } }); if (i % 100 == 0) { System.gc(); } } }
22. LUTCompareTest#main()
Project: openjdk
File: LUTCompareTest.java
File: LUTCompareTest.java
public static void main(String[] args) throws IOException { Image img = createTestImage(); Toolkit tk = Toolkit.getDefaultToolkit(); LUTCompareTest o = new LUTCompareTest(img); tk.prepareImage(img, -1, -1, o); while (!o.isImageReady()) { synchronized (lock) { try { lock.wait(200); } catch (InterruptedException e) { } } } checkResults(img); }
23. MultiResolutionImageTest#testToolkitMultiResolutionImage()
Project: openjdk
File: MultiResolutionImageTest.java
File: MultiResolutionImageTest.java
static void testToolkitMultiResolutionImage() throws Exception { generateImages(); File imageFile = new File(IMAGE_NAME_1X); String fileName = imageFile.getAbsolutePath(); URL url = imageFile.toURI().toURL(); testToolkitMultiResolutionImageChache(fileName, url); Image image = Toolkit.getDefaultToolkit().getImage(fileName); testToolkitImageObserver(image); testToolkitMultiResolutionImage(image, false); testToolkitMultiResolutionImage(image, true); image = Toolkit.getDefaultToolkit().getImage(url); testToolkitImageObserver(image); testToolkitMultiResolutionImage(image, false); testToolkitMultiResolutionImage(image, true); }
24. MultiResolutionImageTest#testToolkitMultiResolutionImageLoad()
Project: openjdk
File: MultiResolutionImageTest.java
File: MultiResolutionImageTest.java
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); }
25. MultiResolutionImageTest#testToolkitMultiResolutionImagePrepare()
Project: openjdk
File: MultiResolutionImageTest.java
File: MultiResolutionImageTest.java
static void testToolkitMultiResolutionImagePrepare() throws Exception { generateImages(); File imageFile = new File(IMAGE_NAME_1X); String fileName = imageFile.getAbsolutePath(); Image image = Toolkit.getDefaultToolkit().getImage(fileName); Toolkit toolkit = Toolkit.getDefaultToolkit(); toolkit.prepareImage(image, IMAGE_WIDTH, IMAGE_HEIGHT, new LoadImageObserver(image)); testToolkitMultiResolutionImageLoad(image); }
26. MultiResolutionImageObserverTest#main()
Project: openjdk
File: MultiResolutionImageObserverTest.java
File: MultiResolutionImageObserverTest.java
public static void main(String[] args) throws Exception { generateImages(); Toolkit toolkit = Toolkit.getDefaultToolkit(); Image image = Toolkit.getDefaultToolkit().getImage(IMAGE_NAME_1X); LoadImageObserver sizeObserver = new LoadImageObserver(WIDTH | HEIGHT); toolkit.prepareImage(image, -1, -1, sizeObserver); waitForImageLoading(sizeObserver, "The first observer is not called"); LoadImageObserver bitsObserver = new LoadImageObserver(SOMEBITS | FRAMEBITS | ALLBITS); BufferedImage buffImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = (Graphics2D) buffImage.createGraphics(); g2d.scale(2, 2); g2d.drawImage(image, 0, 0, bitsObserver); waitForImageLoading(bitsObserver, "The second observer is not called!"); g2d.dispose(); }
27. MultiResolutionToolkitImageTest#testToolkitMultiResolutionImageLoad()
Project: openjdk
File: MultiResolutionToolkitImageTest.java
File: MultiResolutionToolkitImageTest.java
static void testToolkitMultiResolutionImageLoad() throws Exception { File imageFile = new File(IMAGE_NAME_1X); String fileName = imageFile.getAbsolutePath(); Image image = Toolkit.getDefaultToolkit().getImage(fileName); SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); toolkit.prepareImage(image, -1, -1, new LoadImageObserver()); final long time = WAIT_TIME + System.currentTimeMillis(); while ((!isImageLoaded || !isRVObserverCalled) && System.currentTimeMillis() < time) { Thread.sleep(50); } if (!isImageLoaded) { throw new RuntimeException("Image is not loaded!"); } if (!isRVObserverCalled) { throw new RuntimeException("Resolution Variant observer is not called!"); } }
28. MultiResolutionCursorTest#start()
Project: openjdk
File: MultiResolutionCursorTest.java
File: MultiResolutionCursorTest.java
//End init() public void start() { //Get things going. Request focus, set size, et cetera setSize(200, 200); setVisible(true); validate(); final Image image = new BaseMultiResolutionImage(createResolutionVariant(0), createResolutionVariant(1), createResolutionVariant(2), createResolutionVariant(3)); int center = sizes[0] / 2; Cursor cursor = Toolkit.getDefaultToolkit().createCustomCursor(image, new Point(center, center), "multi-resolution cursor"); Frame frame = new Frame("Test Frame"); frame.setSize(300, 300); frame.setLocation(300, 50); frame.add(new Label("Move cursor here")); frame.setCursor(cursor); frame.setVisible(true); }
29. TranslucentWindowPainter#updateWindow()
Project: openjdk
File: TranslucentWindowPainter.java
File: TranslucentWindowPainter.java
/** * Updates the window associated with the painter. * * @param repaint indicates if the window should be completely repainted * to the back buffer using {@link java.awt.Window#paintAll} before update. */ public void updateWindow(boolean repaint) { boolean done = false; Image bb = getBackBuffer(repaint); while (!done) { if (repaint) { Graphics2D g = (Graphics2D) bb.getGraphics(); try { window.paintAll(g); } finally { g.dispose(); } } done = update(bb); if (!done) { repaint = true; bb = getBackBuffer(true); } } }
30. MultiResolutionCachedImage#getResolutionVariant()
Project: openjdk
File: MultiResolutionCachedImage.java
File: MultiResolutionCachedImage.java
@Override public Image getResolutionVariant(double destWidth, double destHeight) { checkSize(destWidth, destHeight); int width = (int) Math.ceil(destWidth); int height = (int) Math.ceil(destHeight); ImageCache cache = ImageCache.getInstance(); ImageCacheKey key = new ImageCacheKey(this, width, height); Image resolutionVariant = cache.getImage(key); if (resolutionVariant == null) { resolutionVariant = mapper.apply(width, height); cache.setImage(key, resolutionVariant); } preload(resolutionVariant, availableInfo); return resolutionVariant; }
31. FileSystemView#getSystemIcon()
Project: openjdk
File: FileSystemView.java
File: FileSystemView.java
public Icon getSystemIcon(File f) { if (f == null) { return null; } ShellFolder sf; try { sf = getShellFolder(f); } catch (FileNotFoundException e) { return null; } Image img = sf.getIcon(false); if (img != null) { return new ImageIcon(img, sf.getFolderType()); } else { return UIManager.getIcon(f.isDirectory() ? "FileView.directoryIcon" : "FileView.fileIcon"); } }
32. BaseMultiResolutionImage#getResolutionVariant()
Project: openjdk
File: BaseMultiResolutionImage.java
File: BaseMultiResolutionImage.java
@Override public Image getResolutionVariant(double destImageWidth, double destImageHeight) { checkSize(destImageWidth, destImageHeight); for (Image rvImage : resolutionVariants) { if (destImageWidth <= rvImage.getWidth(null) && destImageHeight <= rvImage.getHeight(null)) { return rvImage; } } return resolutionVariants[resolutionVariants.length - 1]; }
33. Lookup#scale()
Project: lookup
File: Lookup.java
File: Lookup.java
public static BufferedImage scale(BufferedImage bi, double s, int blurKernel, int px, int py) { bi = filterGausBlur(bi, blurKernel); int cx = (int) (bi.getWidth() * s) + px; int cy = (int) (bi.getHeight() * s) + py; Image src = bi.getScaledInstance(cx, cy, Image.SCALE_SMOOTH); BufferedImage resizedImage = new BufferedImage(cx, cy, bi.getType()); Graphics2D g = resizedImage.createGraphics(); g.drawImage(src, 0, 0, cx, cy, null); g.dispose(); return resizedImage; }
34. GraphicsUtils#loadImage()
Project: LGame
File: GraphicsUtils.java
File: GraphicsUtils.java
public static final Image loadImage(final String name, final byte[] bytes) { if (cacheByteImages.size() > LSystem.DEFAULT_MAX_CACHE_SIZE) { cacheByteImages.clear(); System.gc(); } Image result = null; result = (Image) cacheByteImages.get(name); if (result == null) { try { result = toolKit.createImage(bytes); cacheByteImages.put(name, result); waitImage(result); } catch (Exception e) { result = null; } } return result; }
35. JavaSEGraphicsUtils#loadImage()
Project: LGame
File: JavaSEGraphicsUtils.java
File: JavaSEGraphicsUtils.java
public static final Image loadImage(final String name, final byte[] bytes) { if (cacheByteImages.size() > LSystem.DEFAULT_MAX_CACHE_SIZE) { cacheByteImages.clear(); System.gc(); } Image result = null; result = (Image) cacheByteImages.get(name); if (result == null) { try { result = toolKit.createImage(bytes); cacheByteImages.put(name, result); waitImage(result); } catch (Exception e) { result = null; } } return result; }
36. GraphicsUtils#getImageRows()
Project: LGame
File: GraphicsUtils.java
File: GraphicsUtils.java
/** * ????????? * * @param img * @param width * @return */ public static final Image[] getImageRows(Image img, int width) { int iWidth = img.getWidth(null); int iHeight = img.getHeight(null); int size = iWidth / width; Image[] imgs = new Image[size]; for (int i = 1; i <= size; i++) { try { imgs[i - 1] = transparencyBlackColor(getClipImage(img, width, iHeight, width * (i - 1), 0, width * i, iHeight)); } catch (Exception e) { e.printStackTrace(); } } return imgs; }
37. GraphicsUtils#loadImage()
Project: LGame
File: GraphicsUtils.java
File: GraphicsUtils.java
public static final Image loadImage(final String name, final byte[] bytes) { if (cacheByteImages.size() > LSystem.DEFAULT_MAX_CACHE_SIZE) { cacheByteImages.clear(); System.gc(); } Image result = null; result = (Image) cacheByteImages.get(name); if (result == null) { try { result = toolKit.createImage(bytes); cacheByteImages.put(name, result); waitImage(result); } catch (Exception e) { result = null; } } return result; }
38. mxGraphTransferHandler#createTransferableImage()
Project: jgraphx
File: mxGraphTransferHandler.java
File: mxGraphTransferHandler.java
/** * */ public ImageIcon createTransferableImage(mxGraphComponent graphComponent, Object[] cells) { ImageIcon icon = null; Color bg = (transferImageBackground != null) ? transferImageBackground : graphComponent.getBackground(); Image img = mxCellRenderer.createBufferedImage(graphComponent.getGraph(), cells, 1, bg, graphComponent.isAntiAlias(), null, graphComponent.getCanvas()); if (img != null) { icon = new ImageIcon(img); } return icon; }
39. XYImageAnnotationTest#testEquals()
Project: jfreechart-fse
File: XYImageAnnotationTest.java
File: XYImageAnnotationTest.java
/** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { Image image = getTestImage(); XYImageAnnotation a1 = new XYImageAnnotation(10.0, 20.0, image); XYImageAnnotation a2 = new XYImageAnnotation(10.0, 20.0, image); assertEquals(a1, a2); a1 = new XYImageAnnotation(10.0, 20.0, image, RectangleAnchor.LEFT); assertFalse(a1.equals(a2)); a2 = new XYImageAnnotation(10.0, 20.0, image, RectangleAnchor.LEFT); assertEquals(a1, a2); }
40. NonOpaqueDestLCDAATest#render()
Project: jdk7u-jdk
File: NonOpaqueDestLCDAATest.java
File: NonOpaqueDestLCDAATest.java
public void render(Graphics g, int w, int h) { initImages(w, h); g.setColor(new Color(0xAD, 0xD8, 0xE6)); g.fillRect(0, 0, w, h); Graphics2D g2d = (Graphics2D) g.create(); for (Image im : images) { g2d.drawImage(im, 0, 0, null); g2d.translate(0, im.getHeight(null)); } }
41. AddNoLeak#main()
Project: jdk7u-jdk
File: AddNoLeak.java
File: AddNoLeak.java
public static void main(String[] args) { System.setProperty("java.awt.headless", "true"); Container cont = new Container(); Image img = cont.createImage(new DummyImageSource()); for (int i = 0; i < 15000; i++) { img.getWidth(new ImageObserver() { public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { return false; } }); if (i % 100 == 0) { System.gc(); } } }
42. LUTCompareTest#main()
Project: jdk7u-jdk
File: LUTCompareTest.java
File: LUTCompareTest.java
public static void main(String[] args) throws IOException { Image img = createTestImage(); Toolkit tk = Toolkit.getDefaultToolkit(); LUTCompareTest o = new LUTCompareTest(img); tk.prepareImage(img, -1, -1, o); while (!o.isImageReady()) { synchronized (lock) { try { lock.wait(200); } catch (InterruptedException e) { } } } checkResults(img); }
43. TranslucentWindowPainter#updateWindow()
Project: jdk7u-jdk
File: TranslucentWindowPainter.java
File: TranslucentWindowPainter.java
/** * Updates the window associated with the painter. * * @param repaint indicates if the window should be completely repainted * to the back buffer using {@link java.awt.Window#paintAll} before update. */ public void updateWindow(boolean repaint) { boolean done = false; Image bb = getBackBuffer(repaint); while (!done) { if (repaint) { Graphics2D g = (Graphics2D) bb.getGraphics(); try { window.paintAll(g); } finally { g.dispose(); } } done = update(bb); if (!done) { repaint = true; bb = getBackBuffer(true); } } }
44. FileSystemView#getSystemIcon()
Project: jdk7u-jdk
File: FileSystemView.java
File: FileSystemView.java
public Icon getSystemIcon(File f) { if (f == null) { return null; } ShellFolder sf; try { sf = getShellFolder(f); } catch (FileNotFoundException e) { return null; } Image img = sf.getIcon(false); if (img != null) { return new ImageIcon(img, sf.getFolderType()); } else { return UIManager.getIcon(f.isDirectory() ? "FileView.directoryIcon" : "FileView.fileIcon"); } }
45. LWCanvasPeer#destroyBuffers()
Project: jdk7u-jdk
File: LWCanvasPeer.java
File: LWCanvasPeer.java
@Override public void destroyBuffers() { final Image buffer = getBackBuffer(); if (buffer != null) { synchronized (getStateLock()) { if (buffer == backBuffer) { backBuffer = null; } } buffer.flush(); } }
46. StatusPanel#init()
Project: getdown
File: StatusPanel.java
File: StatusPanel.java
public void init(UpdateInterface ifc, RotatingBackgrounds bg, Image barimg) { _ifc = ifc; _bg = bg; Image img = _bg.getImage(_progress); int width = img == null ? -1 : img.getWidth(this); int height = img == null ? -1 : img.getHeight(this); if (width == -1 || height == -1) { Rectangle bounds = ifc.progress.union(ifc.status); // assume the x inset defines the frame padding; add it on the left, right, and bottom _psize = new Dimension(bounds.x + bounds.width + bounds.x, bounds.y + bounds.height + bounds.x); } else { _psize = new Dimension(width, height); } _barimg = barimg; invalidate(); }
47. IconColorReplacer#getNextIconImages()
Project: freeplane
File: IconColorReplacer.java
File: IconColorReplacer.java
public List<Image> getNextIconImages() { currentColorIndex++; currentColorIndex %= colors.length; Color requiredColor = colors[currentColorIndex]; List<Image> coloredImages = derivedImages.get(requiredColor); if (coloredImages != null) return coloredImages; coloredImages = new ArrayList<Image>(originalIconImages.size()); for (Image originalImage : originalIconImages) { ColoredIconCreator coloredIconCreator = new ColoredIconCreator(originalImage, original); Image coloredImage = coloredIconCreator.createColoredImage(requiredColor); coloredImages.add(coloredImage); } derivedImages.put(requiredColor, coloredImages); return coloredImages; }
48. ImageHelper#getImage()
Project: flex-falcon
File: ImageHelper.java
File: ImageHelper.java
private static Image getImage(byte[] bytes) { Image image; try { image = Toolkit.getDefaultToolkit().createImage(bytes); } catch (InternalError ie) { if (Trace.error) { ie.printStackTrace(); } throw new InternalError("An error occurred because there is no graphics environment available. Please set the headless-server setting in the Flex configuration file to true."); } catch (NoClassDefFoundError ce) { if (Trace.error) { ce.printStackTrace(); } throw new InternalError("An error occurred because there is no graphics environment available. Please set the headless-server setting in the Flex configuration file to true."); } return image; }
49. ImageTranscoder#getImageInfo()
Project: flex-falcon
File: ImageTranscoder.java
File: ImageTranscoder.java
protected ImageInfo getImageInfo(byte[] bytes, Collection<ICompilerProblem> problems) throws Exception { // TODO This gets the image and width of the image. // Need to remove this and come up with a way to get the dimensions // without reading the whole file/using AWT. // http://bugs.adobe.com/jira/browse/CMP-542 Image image = Toolkit.getDefaultToolkit().createImage(bytes); PixelGrabber pixelGrabber = new PixelGrabber(image, 0, 0, -1, -1, true); pixelGrabber.grabPixels(); ImageInfo imageInfo = new ImageInfo(pixelGrabber); return imageInfo; }
50. ImageHandler#loadImage()
Project: ditaa
File: ImageHandler.java
File: ImageHandler.java
public Image loadImage(String filename) { URL url = ClassLoader.getSystemResource(filename); Image result = null; if (url != null) result = Toolkit.getDefaultToolkit().getImage(url); else result = Toolkit.getDefaultToolkit().getImage(filename); // result = null; //wait for the image to load before returning tracker.addImage(result, 0); try { tracker.waitForID(0); } catch (InterruptedException e) { System.err.println("Failed to load image " + filename); e.printStackTrace(); } tracker.removeImage(result, 0); return result; }
51. BitmapRenderer#renderCustomSVGShape()
Project: ditaa
File: BitmapRenderer.java
File: BitmapRenderer.java
private void renderCustomSVGShape(DiagramShape shape, Graphics2D g2) { CustomShapeDefinition definition = shape.getDefinition(); Rectangle bounds = shape.getBounds(); Image graphic; try { if (shape.getFillColor() == null) { graphic = ImageHandler.instance().renderSVG(definition.getFilename(), bounds.width, bounds.height, definition.stretches()); } else { graphic = ImageHandler.instance().renderSVG(definition.getFilename(), bounds.width, bounds.height, definition.stretches(), IDREGEX, shape.getFillColor()); } g2.drawImage(graphic, bounds.x, bounds.y, null); } catch (IOException e) { e.printStackTrace(); } }
52. MultiResolutionCachedImageTest#main()
Project: openjdk
File: MultiResolutionCachedImageTest.java
File: MultiResolutionCachedImageTest.java
public static void main(String[] args) { Image image = new TestMultiResolutionCachedImage(100); image.getWidth(null); image.getHeight(null); image.getProperty("comment", null); int scaledSize = 50; Image scaledImage = image.getScaledInstance(scaledSize, scaledSize, Image.SCALE_SMOOTH); if (!(scaledImage instanceof BufferedImage)) { throw new RuntimeException("Wrong scaled image!"); } BufferedImage buffScaledImage = (BufferedImage) scaledImage; if (buffScaledImage.getWidth() != scaledSize || buffScaledImage.getHeight() != scaledSize) { throw new RuntimeException("Wrong scaled image!"); } if (buffScaledImage.getRGB(scaledSize / 2, scaledSize / 2) != TEST_COLOR.getRGB()) { throw new RuntimeException("Wrong scaled image!"); } }
53. MultiResolutionImageTest#testToolkitMultiResolutionImage()
Project: openjdk
File: MultiResolutionImageTest.java
File: MultiResolutionImageTest.java
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"); } }
54. MultiResolutionImagePropertiesTest#main()
Project: openjdk
File: MultiResolutionImagePropertiesTest.java
File: MultiResolutionImagePropertiesTest.java
public static void main(String[] args) throws Exception { String keys[] = new String[] { "one", "two", "three" }; String otherKeys[] = new String[] { "other", "test" }; String empty[] = new String[] {}; Properties props = new Properties(); for (String k : keys) { props.setProperty(k, PROPS.get(k)); } Properties otherProps = new Properties(); for (String k : otherKeys) { otherProps.setProperty(k, PROPS.get(k)); } Properties defaultProps = new Properties(); // === check the default state === BaseMultiResolutionImage image = new BaseMultiResolutionImage(new BufferedImage[] { generateImage(1, defaultProps), generateImage(2, defaultProps), generateImage(3, defaultProps) }); for (Image var : image.getResolutionVariants()) { if (((BufferedImage) var).getPropertyNames() != null) { throw new RuntimeException("PropertyNames should be null"); } } // === default: base image is the 1st one === image = new BaseMultiResolutionImage(new BufferedImage[] { generateImage(1, props), generateImage(2, otherProps), generateImage(3, defaultProps) }); checkProperties(image, keys, otherKeys); BufferedImage var = (BufferedImage) image.getResolutionVariant(SZ, SZ); checkProperties(var, keys, otherKeys); var = (BufferedImage) image.getResolutionVariant(2 * SZ, 2 * SZ); checkProperties(var, otherKeys, keys); var = (BufferedImage) image.getResolutionVariant(3 * SZ, 3 * SZ); checkProperties(var, empty, keys); checkProperties(var, empty, otherKeys); // === let the 2nd image be a base one === image = new BaseMultiResolutionImage(1, new BufferedImage[] { generateImage(1, props), generateImage(2, otherProps), generateImage(3, defaultProps) }); checkProperties(image, otherKeys, keys); var = (BufferedImage) image.getResolutionVariant(SZ, SZ); checkProperties(var, keys, otherKeys); var = (BufferedImage) image.getResolutionVariant(2 * SZ, 2 * SZ); checkProperties(var, otherKeys, keys); var = (BufferedImage) image.getResolutionVariant(3 * SZ, 3 * SZ); checkProperties(var, empty, keys); checkProperties(var, empty, otherKeys); // === let the 3rd image be a base one === image = new BaseMultiResolutionImage(2, new BufferedImage[] { generateImage(1, defaultProps), generateImage(2, defaultProps), generateImage(3, props) }); checkProperties(image, keys, otherKeys); var = (BufferedImage) image.getResolutionVariant(SZ, SZ); checkProperties(var, empty, keys); checkProperties(var, empty, otherKeys); var = (BufferedImage) image.getResolutionVariant(2 * SZ, 2 * SZ); checkProperties(var, empty, keys); checkProperties(var, empty, otherKeys); var = (BufferedImage) image.getResolutionVariant(3 * SZ, 3 * SZ); checkProperties(var, keys, otherKeys); // === check the other properties don't affect base === checkProperties(new BaseMultiResolutionImage(new BufferedImage[] { generateImage(1, defaultProps), generateImage(2, props), generateImage(3, props) }), empty, keys); checkProperties(new BaseMultiResolutionImage(2, new BufferedImage[] { generateImage(1, props), generateImage(2, props), generateImage(3, defaultProps) }), empty, keys); }
55. ImageFilterTest#test()
Project: openjdk
File: ImageFilterTest.java
File: ImageFilterTest.java
public static void test(MyImageFilter testFilter) { Image image = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB); FilteredImageSource filtered = new FilteredImageSource(image.getSource(), testFilter); Image img = Toolkit.getDefaultToolkit().createImage(filtered); BufferedImage buffImage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); }
56. NSImageToMultiResolutionImageTest#main()
Project: openjdk
File: NSImageToMultiResolutionImageTest.java
File: NSImageToMultiResolutionImageTest.java
public static void main(String[] args) throws Exception { if (OSInfo.getOSType() != OSInfo.OSType.MACOSX) { return; } String icon = "NSImage://NSApplicationIcon"; final Image image = Toolkit.getDefaultToolkit().getImage(icon); if (!(image instanceof MultiResolutionImage)) { throw new RuntimeException("Icon does not have resolution variants!"); } MultiResolutionImage multiResolutionImage = (MultiResolutionImage) image; int width = 0; int height = 0; for (Image resolutionVariant : multiResolutionImage.getResolutionVariants()) { int rvWidth = resolutionVariant.getWidth(null); int rvHeight = resolutionVariant.getHeight(null); if (rvWidth < width || rvHeight < height) { throw new RuntimeException("Resolution variants are not sorted!"); } width = rvWidth; height = rvHeight; } }
57. XYZApp#paint()
Project: openjdk
File: XYZApp.java
File: XYZApp.java
void paint(Graphics gc, int x, int y, int r) { Image ba[] = balls; if (ba == null) { Setup(); ba = balls; } Image i = ba[r]; int size = 10 + r; gc.drawImage(i, x - (size >> 1), y - (size >> 1), size, size, applet); }
58. XYZApp#paint()
Project: jdk7u-jdk
File: XYZApp.java
File: XYZApp.java
void paint(Graphics gc, int x, int y, int r) { Image ba[] = balls; if (ba == null) { Setup(); ba = balls; } Image i = ba[r]; int size = 10 + r; gc.drawImage(i, x - (size >> 1), y - (size >> 1), size, size, applet); }
59. StreamJDKRegistryEntry#handleURL()
Project: cocoon
File: StreamJDKRegistryEntry.java
File: StreamJDKRegistryEntry.java
/** * Decode the URL into a RenderableImage * * @param purl The URLto decode * @param needRawData If true the image returned should not have * any default color correction the file may * specify applied. */ public Filter handleURL(ParsedURL purl, boolean needRawData) { // Read all bytes from the ParsedURL (too bad, there's no Toolkit.createImage(InputStream)) InputStream is = null; byte[] buffer = new byte[1024]; int len; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { is = purl.openStream(); while ((len = is.read(buffer)) != -1) { bos.write(buffer, 0, len); } } catch (IOException ioe) { return null; } finally { try { if (is != null) is.close(); } catch (Exception e) { } } buffer = bos.toByteArray(); Toolkit tk = Toolkit.getDefaultToolkit(); final Image img = tk.createImage(buffer); if (img == null) { return null; } RenderedImage ri = loadImage(img); if (ri == null) { return null; } return new RedRable(GraphicsUtil.wrap(ri)); }
60. PGraphicsJava2D#allocate()
Project: chipKIT32-MAX
File: PGraphicsJava2D.java
File: PGraphicsJava2D.java
// broken out because of subclassing for opengl protected void allocate() { // System.out.println("PGraphicsJava2D allocate() " + width + " " + height); // System.out.println("allocate " + Thread.currentThread().getName()); image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); g2 = (Graphics2D) image.getGraphics(); // can't un-set this because this may be only a resize // http://dev.processing.org/bugs/show_bug.cgi?id=463 //defaultsInited = false; //checkSettings(); //reapplySettings = true; }
61. GradientPanel#paintComponent()
Project: beautyeye
File: GradientPanel.java
File: GradientPanel.java
@Override protected void paintComponent(Graphics g) { Image gradientImage = getGradientImage(); g.drawImage(gradientImage, 0, 0, null); super.paintComponent(g); }
62. FrameDemo#createFrame()
Project: beautyeye
File: FrameDemo.java
File: FrameDemo.java
private static JFrame createFrame() { //<snip>Create frame and set simple properties JFrame frame = new JFrame("Demo JFrame"); frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); //</snip> //<snip>Set Minimized/titlebar icon Image //Note: How the image is used is platform-dependent Image iconImage = null; try { // todo: swingingduke.gif doesn't exist URL imageURL = FrameDemo.class.getResource("resources/images/swingingduke.gif"); iconImage = ImageIO.read(imageURL); } catch (Exception e) { } frame.setIconImage(iconImage); //</snip> //<snip>Make toplevel "busy" // busy glasspane is initially invisible frame.setGlassPane(new BusyGlass()); //</snip> //<snip>Add a menubar JMenuBar menubar = new JMenuBar(); frame.setJMenuBar(menubar); JMenu menu = new JMenu("File"); menubar.add(menu); menu.add("Open"); menu.add("Save"); //</snip> //<snip>Add a horizontal toolbar JToolBar toolbar = new JToolBar(); frame.add(toolbar, BorderLayout.NORTH); toolbar.add(new JButton("Toolbar Button")); //</snip> //<snip>Add the content area JLabel label = new JLabel("I'm content but a little blue."); label.setHorizontalAlignment(JLabel.CENTER); label.setPreferredSize(new Dimension(300, 160)); label.setBackground(new Color(197, 216, 236)); // labels non-opaque by default label.setOpaque(true); frame.add(label); //snip //<snip>Add a statusbar JLabel statusLabel = new JLabel("I show status."); statusLabel.setBorder(new EmptyBorder(4, 4, 4, 4)); statusLabel.setHorizontalAlignment(JLabel.LEADING); frame.add(statusLabel, BorderLayout.SOUTH); //</snip> //<snip>Initialize frame's size to fit it's content frame.pack(); return frame; }
63. Thumbelina#valueChanged()
Project: bboss
File: Thumbelina.java
File: Thumbelina.java
// // ListSelectionListener interface // /** * Handles the history list events. * @param event The event describing the list activity. */ public void valueChanged(final ListSelectionEvent event) { JList source; Object[] hrefs; Picture picture; URL url; Image image; Tracker tracker; source = (JList) event.getSource(); if (source == mHistory && !event.getValueIsAdjusting()) { hrefs = source.getSelectedValues(); for (int i = 0; i < hrefs.length; i++) { picture = mPicturePanel.find("http://" + (String) hrefs[i]); if (null != picture) mPicturePanel.bringToTop(picture); else try { url = new URL("http://" + (String) hrefs[i]); image = getToolkit().createImage(url); tracker = new Tracker(url); image.getWidth(tracker); System.out.println("refetching " + hrefs[i]); } catch (MalformedURLException murle) { murle.printStackTrace(); } } } }
64. Thumbelina#fetch()
Project: bboss
File: Thumbelina.java
File: Thumbelina.java
/** * Fetch images. * Ask the toolkit to make the image from a URL, and add a tracker * to handle it when it's received. * Add details to the rquested and tracked lists and update * the status bar. * @param images The list of images to fetch. */ protected void fetch(final URL[] images) { Image image; Tracker tracker; int size; for (int j = 0; j < images.length; j++) { if (!mRequested.containsKey(images[j].toExternalForm())) { image = getToolkit().createImage(images[j]); tracker = new Tracker(images[j]); synchronized (mTracked) { size = mTracked.size() + 1; if (mQueueProgress.getMaximum() < size) { try { mTracked.wait(); } catch (InterruptedException ie) { } } mRequested.put(images[j].toExternalForm(), images[j]); mTracked.put(images[j].toExternalForm(), images[j]); mQueueProgress.setValue(size); // trigger the observer image.getWidth(tracker); } } } }
65. PicturePanel#paint()
Project: bboss
File: PicturePanel.java
File: PicturePanel.java
/** * Paints this component. * Runs through the list of tiles and for every one that intersects * the clip region performs a <code>drawImage()</code>. * @param graphics The graphics context used to paint with. */ public void paint(final Graphics graphics) { Rectangle clip; Iterator enumeration; // just so we don't draw things twice HashSet set; Picture picture; Image image; Point origin; int width; int height; adjustClipForInsets(graphics); clip = graphics.getClipBounds(); synchronized (mMosaic) { if (0 == mMosaic.getSize()) super.paint(graphics); else { super.paint(graphics); enumeration = mMosaic.getPictures(); set = new HashSet(); while (enumeration.hasNext()) { picture = (Picture) enumeration.next(); if ((null == clip) || (clip.intersects(picture))) { image = picture.getImage(); if (!set.contains(image)) { origin = picture.getOrigin(); width = image.getWidth(this); height = image.getHeight(this); graphics.drawImage(picture.getImage(), origin.x, origin.y, origin.x + width, origin.y + height, 0, 0, width, height, this); set.add(image); } } } } } }
66. GraphicObjects#paint()
Project: batik
File: GraphicObjects.java
File: GraphicObjects.java
public void paint(Graphics2D g) { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // Text g.setPaint(Color.black); g.setFont(new Font("Times New Roman", Font.PLAIN, 20)); g.drawString("Hello SVG drawString(...)", 20, 40); g.translate(0, 70); // Shapes Ellipse2D ellipse = new Ellipse2D.Float(20, 0, 60, 60); g.setPaint(new Color(176, 22, 40)); g.fill(ellipse); g.translate(60, 0); g.setPaint(new Color(208, 170, 119)); g.fill(ellipse); g.translate(60, 0); g.setPaint(new Color(221, 229, 111)); g.fill(ellipse); g.translate(60, 0); g.setPaint(new Color(240, 165, 0)); g.fill(ellipse); g.translate(-180, 60); // Draw background pattern BufferedImage pattern = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB); Graphics2D ig = pattern.createGraphics(); ig.setPaint(Color.white); ig.fillRect(0, 0, 10, 10); ig.setPaint(new Color(0xaaaaaa)); ig.fillRect(0, 0, 5, 5); ig.fillRect(5, 5, 5, 50); TexturePaint texture = new TexturePaint(pattern, new Rectangle(0, 0, 10, 10)); // Image BufferedImage image = new BufferedImage(200, 150, BufferedImage.TYPE_INT_ARGB); ig = image.createGraphics(); ig.setPaint(texture); ig.fillRect(0, 0, 200, 150); g.drawImage(image, 40, 40, null); image = new BufferedImage(200, 150, BufferedImage.TYPE_INT_ARGB); ig = image.createGraphics(); GradientPaint paint = new GradientPaint(0, 0, new Color(103, 103, 152), 200, 150, new Color(103, 103, 152, 0)); ig.setPaint(paint); ig.fillRect(0, 0, 200, 150); ig.setPaint(Color.black); ig.setFont(new Font("Arial", Font.PLAIN, 10)); ig.drawString("This is an image with alpha", 10, 30); ig.dispose(); g.drawImage(image, 40, 40, null); }
67. PNGEncoderTest#runImpl()
Project: batik
File: PNGEncoderTest.java
File: PNGEncoderTest.java
public TestReport runImpl() throws Exception { // Create a BufferedImage to be encoded BufferedImage image = new BufferedImage(100, 75, BufferedImage.TYPE_INT_ARGB); Graphics2D ig = image.createGraphics(); ig.scale(.5, .5); ig.setPaint(new Color(128, 0, 0)); ig.fillRect(0, 0, 100, 50); ig.setPaint(Color.orange); ig.fillRect(100, 0, 100, 50); ig.setPaint(Color.yellow); ig.fillRect(0, 50, 100, 50); ig.setPaint(Color.red); ig.fillRect(100, 50, 100, 50); ig.setPaint(new Color(255, 127, 127)); ig.fillRect(0, 100, 100, 50); ig.setPaint(Color.black); ig.draw(new Rectangle2D.Double(0.5, 0.5, 199, 149)); ig.dispose(); image = image.getSubimage(50, 0, 50, 25); // Create an output stream where the PNG data // will be stored. ByteArrayOutputStream bos = new ByteArrayOutputStream(); OutputStream os = buildOutputStream(bos); // Now, try to encode image PNGEncodeParam params = PNGEncodeParam.getDefaultEncodeParam(image); PNGImageEncoder pngImageEncoder = new PNGImageEncoder(os, params); try { pngImageEncoder.encode(image); os.close(); } catch (Exception e) { return reportException(ERROR_CANNOT_ENCODE_IMAGE, e); } // Now, try to decode image InputStream is = buildInputStream(bos); PNGImageDecoder pngImageDecoder = new PNGImageDecoder(is, new PNGDecodeParam()); RenderedImage decodedRenderedImage = null; try { decodedRenderedImage = pngImageDecoder.decodeAsRenderedImage(0); } catch (Exception e) { return reportException(ERROR_CANNOT_DECODE_IMAGE, e); } BufferedImage decodedImage = null; if (decodedRenderedImage instanceof BufferedImage) { decodedImage = (BufferedImage) decodedRenderedImage; } else { decodedImage = new BufferedImage(decodedRenderedImage.getWidth(), decodedRenderedImage.getHeight(), BufferedImage.TYPE_INT_ARGB); ig = decodedImage.createGraphics(); ig.drawRenderedImage(decodedRenderedImage, new AffineTransform()); ig.dispose(); } // Compare images if (!checkIdentical(image, decodedImage)) { return reportError(ERROR_DECODED_DOES_NOT_MATCH_ENCODED); } return reportSuccess(); }
68. Rescale#paint()
Project: batik
File: Rescale.java
File: Rescale.java
public void paint(Graphics2D g) { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // // Load Image // Image image = Toolkit.getDefaultToolkit().createImage("test-resources/org/apache/batik/svggen/resources/vangogh.jpg"); MediaTracker tracker = new MediaTracker(new Button("")); tracker.addImage(image, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { tracker.removeImage(image); image = null; } finally { if (image != null) tracker.removeImage(image); if (tracker.isErrorAny()) image = null; if (image != null) { if (image.getWidth(null) < 0 || image.getHeight(null) < 0) image = null; } } if (image == null) { throw new Error("Could not load image"); } BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D ig = bi.createGraphics(); ig.drawImage(image, 0, 0, null); java.awt.image.RescaleOp brighten = new java.awt.image.RescaleOp(1.5f, 0, null); java.awt.image.RescaleOp darken = new java.awt.image.RescaleOp(.6f, 0, null); // Simply paint the image without and with rescale filters g.setPaint(Color.black); g.drawString("Brighter / Normal / Darker", 10, 20); g.drawImage(bi, brighten, 10, 30); g.drawImage(image, 10 + bi.getWidth() + 10, 30, null); g.drawImage(bi, darken, 10 + 2 * (bi.getWidth() + 10), 30); g.translate(0, bi.getHeight() + 30 + 20); g.drawString("Rescale Red / Green / Blue", 10, 20); java.awt.image.RescaleOp redStress = new java.awt.image.RescaleOp(new float[] { 2.0f, 1.0f, 1.0f }, new float[] { 0, 0, 0 }, null); java.awt.image.RescaleOp greenStress = new java.awt.image.RescaleOp(new float[] { 1.0f, 2.0f, 1.0f }, new float[] { 0, 0, 0 }, null); java.awt.image.RescaleOp blueStress = new java.awt.image.RescaleOp(new float[] { 1.0f, 1.0f, 2.0f }, new float[] { 0, 0, 0 }, null); g.drawImage(bi, redStress, 10, 30); g.drawImage(bi, greenStress, 10 + bi.getWidth() + 10, 30); g.drawImage(bi, blueStress, 10 + 2 * (bi.getWidth() + 10), 30); }
69. Lookup#paint()
Project: batik
File: Lookup.java
File: Lookup.java
public void paint(Graphics2D g) { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // // Load Image // Image image = Toolkit.getDefaultToolkit().createImage("test-resources/org/apache/batik/svggen/resources/vangogh.png"); MediaTracker tracker = new MediaTracker(new Button("")); tracker.addImage(image, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { tracker.removeImage(image); image = null; } finally { if (image != null) tracker.removeImage(image); if (tracker.isErrorAny()) image = null; if (image != null) { if (image.getWidth(null) < 0 || image.getHeight(null) < 0) image = null; } } if (image == null) { throw new Error("Could not load image"); } BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D ig = bi.createGraphics(); ig.drawImage(image, 0, 0, null); byte[] lookup = new byte[256]; for (int i = 0; i < 256; i++) lookup[i] = (byte) (255 - i); LookupTable table = new ByteLookupTable(0, lookup); java.awt.image.LookupOp inverter = new java.awt.image.LookupOp(table, null); // Simply paint the image without and with the lookup filter g.setPaint(Color.black); g.drawString("Normal / Inverted", 10, 20); g.drawImage(image, 10, 30, null); g.drawImage(bi, inverter, 10 + bi.getWidth() + 10, 30); }
70. CursorManager#convertSVGCursorElement()
Project: batik
File: CursorManager.java
File: CursorManager.java
/** * Returns a cursor for a given element */ public Cursor convertSVGCursorElement(Element cursorElement) { // One of the cursor url resolved to a <cursor> element // Try to handle its image. String uriStr = XLinkSupport.getXLinkHref(cursorElement); if (uriStr.length() == 0) { throw new BridgeException(ctx, cursorElement, ERR_ATTRIBUTE_MISSING, new Object[] { "xlink:href" }); } String baseURI = AbstractNode.getBaseURI(cursorElement); ParsedURL purl; if (baseURI == null) { purl = new ParsedURL(uriStr); } else { purl = new ParsedURL(baseURI, uriStr); } // // Convert the cursor's hot spot // UnitProcessor.Context uctx = UnitProcessor.createContext(ctx, cursorElement); String s = cursorElement.getAttributeNS(null, SVG_X_ATTRIBUTE); float x = 0; if (s.length() != 0) { x = UnitProcessor.svgHorizontalCoordinateToUserSpace(s, SVG_X_ATTRIBUTE, uctx); } s = cursorElement.getAttributeNS(null, SVG_Y_ATTRIBUTE); float y = 0; if (s.length() != 0) { y = UnitProcessor.svgVerticalCoordinateToUserSpace(s, SVG_Y_ATTRIBUTE, uctx); } CursorDescriptor desc = new CursorDescriptor(purl, x, y); // // Check if there is a cursor in the cache for this url // Cursor cachedCursor = cursorCache.getCursor(desc); if (cachedCursor != null) { return cachedCursor; } // // Load image into Filter f and transform hotSpot to // cursor space. // Point2D.Float hotSpot = new Point2D.Float(x, y); Filter f = cursorHrefToFilter(cursorElement, purl, hotSpot); if (f == null) { cursorCache.clearCursor(desc); return null; } // The returned Filter is guaranteed to create a // default rendering of the desired size Rectangle cursorSize = f.getBounds2D().getBounds(); RenderedImage ri = f.createScaledRendering(cursorSize.width, cursorSize.height, null); Image img = null; if (ri instanceof Image) { img = (Image) ri; } else { img = renderedImageToImage(ri); } // Make sure the not spot does not fall out of the cursor area. If it // does, then clamp the coordinates to the image space. hotSpot.x = hotSpot.x < 0 ? 0 : hotSpot.x; hotSpot.y = hotSpot.y < 0 ? 0 : hotSpot.y; hotSpot.x = hotSpot.x > (cursorSize.width - 1) ? cursorSize.width - 1 : hotSpot.x; hotSpot.y = hotSpot.y > (cursorSize.height - 1) ? cursorSize.height - 1 : hotSpot.y; // // The cursor image is now into 'img' // Cursor c = Toolkit.getDefaultToolkit().createCustomCursor(img, new Point(Math.round(hotSpot.x), Math.round(hotSpot.y)), purl.toString()); cursorCache.putCursor(desc, c); return c; }
71. MtomSampleTests#testSendImage_setMTOMThreshold()
Project: axis2-java
File: MtomSampleTests.java
File: MtomSampleTests.java
/* * Enable attachment Optimization but call an endpoint with @MTOM(enable=true, Threshold = 99000) */ public void testSendImage_setMTOMThreshold() throws Exception { TestLogger.logger.debug("----------------------------------"); TestLogger.logger.debug("test: " + getName()); System.out.println("testSendImage_setMTOMThreshold()"); String imageResourceDir = IMAGE_DIR; //Create a DataSource from an image File file = new File(imageResourceDir + File.separator + "test.jpg"); ImageInputStream fiis = new FileImageInputStream(file); Image image = ImageIO.read(fiis); DataSource imageDS = new DataSourceImpl("image/jpeg", "test.jpg", image); //Create a DataHandler with the String DataSource object DataHandler dataHandler = new DataHandler(imageDS); //Store the data handler in ImageDepot bean ImageDepot imageDepot = new ObjectFactory().createImageDepot(); imageDepot.setImageData(dataHandler); SendImage request = new ObjectFactory().createSendImage(); request.setInput(imageDepot); //Create the necessary JAXBContext JAXBContext jbc = JAXBContext.newInstance("org.test.mtom"); //Setting Threshold to send request Inline int threshold = 100000; MTOMFeature mtom21 = new MTOMFeature(true, threshold); // Create the JAX-WS client needed to send the request Service service = Service.create(QNAME_SERVICE); service.addPort(QNAME_PORT, SOAPBinding.SOAP11HTTP_BINDING, URL_ENDPOINT_MTOMTHRESHOLD); Dispatch<Object> dispatch = service.createDispatch(QNAME_PORT, jbc, Mode.PAYLOAD, mtom21); List cids = null; SendImageResponse response = null; try { JAXBAttachmentUnmarshallerMonitor.setMonitoring(true); response = (SendImageResponse) dispatch.invoke(request); // The cids are collected in the monitor. We will check // this to make sure the response mtom is not inlined cids = JAXBAttachmentUnmarshallerMonitor.getBlobCIDs(); } finally { JAXBAttachmentUnmarshallerMonitor.setMonitoring(false); } assertNotNull(response); assertNotNull(response.getOutput().getImageData()); //There shold be no cid as attachment should be inlined. int numCIDs = (cids == null) ? 0 : cids.size(); assertTrue("Expected one attachment inlined:" + numCIDs, numCIDs == 0); // Repeat to verify behavior response = null; try { JAXBAttachmentUnmarshallerMonitor.setMonitoring(true); response = (SendImageResponse) dispatch.invoke(request); // The cids are collected in the monitor. We will check // this to make sure the response mtom is not inlined cids = JAXBAttachmentUnmarshallerMonitor.getBlobCIDs(); } finally { JAXBAttachmentUnmarshallerMonitor.setMonitoring(false); } assertNotNull(response); assertNotNull(response.getOutput().getImageData()); //There shold be no cid as attachment should be inlined. numCIDs = (cids == null) ? 0 : cids.size(); assertTrue("Expected one attachment inlined:" + numCIDs, numCIDs == 0); }
72. MtomSampleTests#testSendImageAttachmentAPI12()
Project: axis2-java
File: MtomSampleTests.java
File: MtomSampleTests.java
/* * Enable attachment optimization using both the SOAP12 binding API * for MTOM * * Sending SOAP12 message to SOAP11 endpoint will correctly result in exception * */ public void testSendImageAttachmentAPI12() throws Exception { TestLogger.logger.debug("----------------------------------"); TestLogger.logger.debug("test: " + getName()); String imageResourceDir = IMAGE_DIR; //Create a DataSource from an image File file = new File(imageResourceDir + File.separator + "test.jpg"); ImageInputStream fiis = new FileImageInputStream(file); Image image = ImageIO.read(fiis); DataSource imageDS = new DataSourceImpl("image/jpeg", "test.jpg", image); //Create a DataHandler with the String DataSource object DataHandler dataHandler = new DataHandler(imageDS); //Store the data handler in ImageDepot bean ImageDepot imageDepot = new ObjectFactory().createImageDepot(); imageDepot.setImageData(dataHandler); SendImage request = new ObjectFactory().createSendImage(); request.setInput(imageDepot); //Create the necessary JAXBContext JAXBContext jbc = JAXBContext.newInstance("org.test.mtom"); // Create the JAX-WS client needed to send the request with soap 11 binding // property for MTOM Service service = Service.create(QNAME_SERVICE); service.addPort(QNAME_PORT, SOAPBinding.SOAP12HTTP_BINDING, URL_ENDPOINT); Dispatch<Object> dispatch = service.createDispatch(QNAME_PORT, jbc, Mode.PAYLOAD); //Enable attachment optimization SOAPBinding binding = (SOAPBinding) dispatch.getBinding(); binding.setMTOMEnabled(true); try { SendImageResponse response = (SendImageResponse) dispatch.invoke(request); fail("Was expecting an exception due to sending SOAP12 message to SOAP11 endpoint."); } catch (Exception e) { assertNotNull(e); if (CHECK_VERSIONMISMATCH) { assertTrue("Expected SOAPFaultException, but received: " + e.getClass(), e instanceof SOAPFaultException); SOAPFaultException sfe = (SOAPFaultException) e; SOAPFault fault = sfe.getFault(); assertTrue("SOAPFault is null ", fault != null); QName faultCode = sfe.getFault().getFaultCodeAsQName(); assertTrue("Expected VERSION MISMATCH but received: " + faultCode, new QName(SOAPConstants.URI_NS_SOAP_1_1_ENVELOPE, "VersionMismatch", SOAPConstants.SOAP_ENV_PREFIX).equals(faultCode)); } } // Repeat to verify behavior try { SendImageResponse response = (SendImageResponse) dispatch.invoke(request); fail("Was expecting an exception due to sending SOAP12 message to SOAP11 endpoint."); } catch (Exception e) { assertNotNull(e); if (CHECK_VERSIONMISMATCH) { assertTrue("Expected SOAPFaultException, but received: " + e.getClass(), e instanceof SOAPFaultException); SOAPFaultException sfe = (SOAPFaultException) e; SOAPFault fault = sfe.getFault(); assertTrue("SOAPFault is null ", fault != null); QName faultCode = sfe.getFault().getFaultCodeAsQName(); assertTrue("Expected VERSION MISMATCH but received: " + faultCode, new QName(SOAPConstants.URI_NS_SOAP_1_1_ENVELOPE, "VersionMismatch", SOAPConstants.SOAP_ENV_PREFIX).equals(faultCode)); } } }
73. MtomSampleTests#testSendImageAttachmentProperty12()
Project: axis2-java
File: MtomSampleTests.java
File: MtomSampleTests.java
/* * Enable attachment optimization using both the SOAP12 binding * property for MTOM * * Sending SOAP12 message to SOAP11 endpoint will correctly result in exception * */ public void testSendImageAttachmentProperty12() throws Exception { TestLogger.logger.debug("----------------------------------"); TestLogger.logger.debug("test: " + getName()); String imageResourceDir = IMAGE_DIR; //Create a DataSource from an image File file = new File(imageResourceDir + File.separator + "test.jpg"); ImageInputStream fiis = new FileImageInputStream(file); Image image = ImageIO.read(fiis); DataSource imageDS = new DataSourceImpl("image/jpeg", "test.jpg", image); //Create a DataHandler with the String DataSource object DataHandler dataHandler = new DataHandler(imageDS); //Store the data handler in ImageDepot bean ImageDepot imageDepot = new ObjectFactory().createImageDepot(); imageDepot.setImageData(dataHandler); SendImage request = new ObjectFactory().createSendImage(); request.setInput(imageDepot); //Create the necessary JAXBContext JAXBContext jbc = JAXBContext.newInstance("org.test.mtom"); // Create the JAX-WS client needed to send the request with soap 11 binding // property for MTOM Service service = Service.create(QNAME_SERVICE); service.addPort(QNAME_PORT, SOAPBinding.SOAP12HTTP_MTOM_BINDING, URL_ENDPOINT); Dispatch<Object> dispatch = service.createDispatch(QNAME_PORT, jbc, Mode.PAYLOAD); try { SendImageResponse response = (SendImageResponse) dispatch.invoke(request); fail("Was expecting an exception due to sending SOAP12 message to SOAP11 endpoint."); } catch (Exception e) { assertNotNull(e); if (CHECK_VERSIONMISMATCH) { assertTrue("Expected SOAPFaultException, but received: " + e.getClass(), e instanceof SOAPFaultException); SOAPFaultException sfe = (SOAPFaultException) e; SOAPFault fault = sfe.getFault(); assertTrue("SOAPFault is null ", fault != null); QName faultCode = sfe.getFault().getFaultCodeAsQName(); assertTrue("Expected VERSION MISMATCH but received: " + faultCode, new QName(SOAPConstants.URI_NS_SOAP_1_1_ENVELOPE, "VersionMismatch", SOAPConstants.SOAP_ENV_PREFIX).equals(faultCode)); } } // Repeat to verify behavior try { SendImageResponse response = (SendImageResponse) dispatch.invoke(request); fail("Was expecting an exception due to sending SOAP12 message to SOAP11 endpoint."); } catch (Exception e) { assertNotNull(e); if (CHECK_VERSIONMISMATCH) { assertTrue("Expected SOAPFaultException, but received: " + e.getClass(), e instanceof SOAPFaultException); SOAPFaultException sfe = (SOAPFaultException) e; SOAPFault fault = sfe.getFault(); assertTrue("SOAPFault is null ", fault != null); QName faultCode = sfe.getFault().getFaultCodeAsQName(); assertTrue("Expected VERSION MISMATCH but received: " + faultCode, new QName(SOAPConstants.URI_NS_SOAP_1_1_ENVELOPE, "VersionMismatch", SOAPConstants.SOAP_ENV_PREFIX).equals(faultCode)); } } }
74. MtomSampleTests#testSendImageAttachmentAPIProperty11()
Project: axis2-java
File: MtomSampleTests.java
File: MtomSampleTests.java
/* * Enable attachment optimization using both the SOAP11 binding * property for MTOM and the Binding API */ public void testSendImageAttachmentAPIProperty11() throws Exception { TestLogger.logger.debug("----------------------------------"); TestLogger.logger.debug("test: " + getName()); String imageResourceDir = IMAGE_DIR; //Create a DataSource from an image File file = new File(imageResourceDir + File.separator + "test.jpg"); ImageInputStream fiis = new FileImageInputStream(file); Image image = ImageIO.read(fiis); DataSource imageDS = new DataSourceImpl("image/jpeg", "test.jpg", image); //Create a DataHandler with the String DataSource object DataHandler dataHandler = new DataHandler(imageDS); //Store the data handler in ImageDepot bean ImageDepot imageDepot = new ObjectFactory().createImageDepot(); imageDepot.setImageData(dataHandler); SendImage request = new ObjectFactory().createSendImage(); request.setInput(imageDepot); //Create the necessary JAXBContext JAXBContext jbc = JAXBContext.newInstance("org.test.mtom"); // Create the JAX-WS client needed to send the request with soap 11 binding // property for MTOM Service service = Service.create(QNAME_SERVICE); service.addPort(QNAME_PORT, SOAPBinding.SOAP11HTTP_MTOM_BINDING, URL_ENDPOINT); Dispatch<Object> dispatch = service.createDispatch(QNAME_PORT, jbc, Mode.PAYLOAD); //Enable attachment optimization SOAPBinding binding = (SOAPBinding) dispatch.getBinding(); binding.setMTOMEnabled(true); SendImageResponse response = (SendImageResponse) dispatch.invoke(request); assertNotNull(response); assertNotNull(response.getOutput().getImageData()); // Repeat to verify behavior response = (SendImageResponse) dispatch.invoke(request); assertNotNull(response); assertNotNull(response.getOutput().getImageData()); }
75. MtomSampleTests#testSendImageAttachmentProperty11()
Project: axis2-java
File: MtomSampleTests.java
File: MtomSampleTests.java
/* * Enable attachment optimization using the SOAP11 binding * property for MTOM. */ public void testSendImageAttachmentProperty11() throws Exception { TestLogger.logger.debug("----------------------------------"); TestLogger.logger.debug("test: " + getName()); String imageResourceDir = IMAGE_DIR; //Create a DataSource from an image File file = new File(imageResourceDir + File.separator + "test.jpg"); ImageInputStream fiis = new FileImageInputStream(file); Image image = ImageIO.read(fiis); DataSource imageDS = new DataSourceImpl("image/jpeg", "test.jpg", image); //Create a DataHandler with the String DataSource object DataHandler dataHandler = new DataHandler(imageDS); //Store the data handler in ImageDepot bean ImageDepot imageDepot = new ObjectFactory().createImageDepot(); imageDepot.setImageData(dataHandler); SendImage request = new ObjectFactory().createSendImage(); request.setInput(imageDepot); //Create the necessary JAXBContext JAXBContext jbc = JAXBContext.newInstance("org.test.mtom"); // Create the JAX-WS client needed to send the request with soap 11 binding // property for MTOM Service service = Service.create(QNAME_SERVICE); service.addPort(QNAME_PORT, SOAPBinding.SOAP11HTTP_MTOM_BINDING, URL_ENDPOINT); Dispatch<Object> dispatch = service.createDispatch(QNAME_PORT, jbc, Mode.PAYLOAD); SendImageResponse response = (SendImageResponse) dispatch.invoke(request); assertNotNull(response); assertNotNull(response.getOutput().getImageData()); // Repeat to verify behavior response = (SendImageResponse) dispatch.invoke(request); assertNotNull(response); assertNotNull(response.getOutput().getImageData()); }
76. MtomSampleTests#testSendImage_MTOMDefault()
Project: axis2-java
File: MtomSampleTests.java
File: MtomSampleTests.java
/* * Enable attachment Optimization but call an endpoint with @MTOM */ public void testSendImage_MTOMDefault() throws Exception { TestLogger.logger.debug("----------------------------------"); TestLogger.logger.debug("test: " + getName()); String imageResourceDir = IMAGE_DIR; //Create a DataSource from an image File file = new File(imageResourceDir + File.separator + "test.jpg"); ImageInputStream fiis = new FileImageInputStream(file); Image image = ImageIO.read(fiis); DataSource imageDS = new DataSourceImpl("image/jpeg", "test.jpg", image); //Create a DataHandler with the String DataSource object DataHandler dataHandler = new DataHandler(imageDS); //Store the data handler in ImageDepot bean ImageDepot imageDepot = new ObjectFactory().createImageDepot(); imageDepot.setImageData(dataHandler); SendImage request = new ObjectFactory().createSendImage(); request.setInput(imageDepot); //Create the necessary JAXBContext JAXBContext jbc = JAXBContext.newInstance("org.test.mtom"); MTOMFeature mtom21 = new MTOMFeature(); // Create the JAX-WS client needed to send the request Service service = Service.create(QNAME_SERVICE); service.addPort(QNAME_PORT, SOAPBinding.SOAP11HTTP_BINDING, URL_ENDPOINT_MTOMDEFAULT); Dispatch<Object> dispatch = service.createDispatch(QNAME_PORT, jbc, Mode.PAYLOAD, mtom21); List cids = null; SendImageResponse response = null; try { JAXBAttachmentUnmarshallerMonitor.setMonitoring(true); response = (SendImageResponse) dispatch.invoke(request); // The cids are collected in the monitor. We will check // this to make sure the response mtom is not inlined cids = JAXBAttachmentUnmarshallerMonitor.getBlobCIDs(); } finally { JAXBAttachmentUnmarshallerMonitor.setMonitoring(false); } assertNotNull(response); assertNotNull(response.getOutput().getImageData()); int numCIDs = (cids == null) ? 0 : cids.size(); assertTrue("Expected one attachment but there were:" + numCIDs, numCIDs == 1); // Repeat to verify behavior response = null; try { JAXBAttachmentUnmarshallerMonitor.setMonitoring(true); response = (SendImageResponse) dispatch.invoke(request); // The cids are collected in the monitor. We will check // this to make sure the response mtom is not inlined cids = JAXBAttachmentUnmarshallerMonitor.getBlobCIDs(); } finally { JAXBAttachmentUnmarshallerMonitor.setMonitoring(false); } assertNotNull(response); assertNotNull(response.getOutput().getImageData()); numCIDs = (cids == null) ? 0 : cids.size(); assertTrue("Expected one attachment but there were:" + numCIDs, numCIDs == 1); }
77. MtomSampleTests#testSendImage_MTOMEnable()
Project: axis2-java
File: MtomSampleTests.java
File: MtomSampleTests.java
/* * Enable attachment Optimization but call an endpoint with @MTOM(enable=true) */ public void testSendImage_MTOMEnable() throws Exception { TestLogger.logger.debug("----------------------------------"); TestLogger.logger.debug("test: " + getName()); String imageResourceDir = IMAGE_DIR; //Create a DataSource from an image File file = new File(imageResourceDir + File.separator + "test.jpg"); ImageInputStream fiis = new FileImageInputStream(file); Image image = ImageIO.read(fiis); DataSource imageDS = new DataSourceImpl("image/jpeg", "test.jpg", image); //Create a DataHandler with the String DataSource object DataHandler dataHandler = new DataHandler(imageDS); //Store the data handler in ImageDepot bean ImageDepot imageDepot = new ObjectFactory().createImageDepot(); imageDepot.setImageData(dataHandler); SendImage request = new ObjectFactory().createSendImage(); request.setInput(imageDepot); //Create the necessary JAXBContext JAXBContext jbc = JAXBContext.newInstance("org.test.mtom"); MTOMFeature mtom21 = new MTOMFeature(); // Create the JAX-WS client needed to send the request Service service = Service.create(QNAME_SERVICE); service.addPort(QNAME_PORT, SOAPBinding.SOAP11HTTP_BINDING, URL_ENDPOINT_MTOMENABLE); Dispatch<Object> dispatch = service.createDispatch(QNAME_PORT, jbc, Mode.PAYLOAD, mtom21); List cids = null; SendImageResponse response = null; try { JAXBAttachmentUnmarshallerMonitor.setMonitoring(true); response = (SendImageResponse) dispatch.invoke(request); // The cids are collected in the monitor. We will check // this to make sure the response mtom is not inlined cids = JAXBAttachmentUnmarshallerMonitor.getBlobCIDs(); } finally { JAXBAttachmentUnmarshallerMonitor.setMonitoring(false); } assertNotNull(response); assertNotNull(response.getOutput().getImageData()); int numCIDs = (cids == null) ? 0 : cids.size(); assertTrue("Expected one attachment but there were:" + numCIDs, numCIDs == 1); // Repeat to verify behavior response = null; try { JAXBAttachmentUnmarshallerMonitor.setMonitoring(true); response = (SendImageResponse) dispatch.invoke(request); // The cids are collected in the monitor. We will check // this to make sure the response mtom is not inlined cids = JAXBAttachmentUnmarshallerMonitor.getBlobCIDs(); } finally { JAXBAttachmentUnmarshallerMonitor.setMonitoring(false); } assertNotNull(response); assertNotNull(response.getOutput().getImageData()); numCIDs = (cids == null) ? 0 : cids.size(); assertTrue("Expected one attachment but there were:" + numCIDs, numCIDs == 1); }
78. MtomSampleTests#testSendImage_MTOMDisable2()
Project: axis2-java
File: MtomSampleTests.java
File: MtomSampleTests.java
/* * Enable attachment Optimization but call an endpoint with @MTOM(enable=false) * which should override the MTOM BindingType */ public void testSendImage_MTOMDisable2() throws Exception { TestLogger.logger.debug("----------------------------------"); TestLogger.logger.debug("test: " + getName()); String imageResourceDir = IMAGE_DIR; //Create a DataSource from an image File file = new File(imageResourceDir + File.separator + "test.jpg"); ImageInputStream fiis = new FileImageInputStream(file); Image image = ImageIO.read(fiis); DataSource imageDS = new DataSourceImpl("image/jpeg", "test.jpg", image); //Create a DataHandler with the String DataSource object DataHandler dataHandler = new DataHandler(imageDS); //Store the data handler in ImageDepot bean ImageDepot imageDepot = new ObjectFactory().createImageDepot(); imageDepot.setImageData(dataHandler); SendImage request = new ObjectFactory().createSendImage(); request.setInput(imageDepot); //Create the necessary JAXBContext JAXBContext jbc = JAXBContext.newInstance("org.test.mtom"); MTOMFeature mtom21 = new MTOMFeature(); // Create the JAX-WS client needed to send the request Service service = Service.create(QNAME_SERVICE); service.addPort(QNAME_PORT, SOAPBinding.SOAP11HTTP_BINDING, URL_ENDPOINT_MTOMDISABLE2); Dispatch<Object> dispatch = service.createDispatch(QNAME_PORT, jbc, Mode.PAYLOAD, mtom21); List cids = null; SendImageResponse response = null; try { JAXBAttachmentUnmarshallerMonitor.setMonitoring(true); response = (SendImageResponse) dispatch.invoke(request); // The cids are collected in the monitor. We will check // this to make sure the response mtom is not inlined cids = JAXBAttachmentUnmarshallerMonitor.getBlobCIDs(); } finally { JAXBAttachmentUnmarshallerMonitor.setMonitoring(false); } assertNotNull(response); assertNotNull(response.getOutput().getImageData()); int numCIDs = (cids == null) ? 0 : cids.size(); assertTrue("Expected zero attachments but there were:" + numCIDs, numCIDs == 0); // Repeat to verify behavior response = null; try { JAXBAttachmentUnmarshallerMonitor.setMonitoring(true); response = (SendImageResponse) dispatch.invoke(request); // The cids are collected in the monitor. We will check // this to make sure the response mtom is not inlined cids = JAXBAttachmentUnmarshallerMonitor.getBlobCIDs(); } finally { JAXBAttachmentUnmarshallerMonitor.setMonitoring(false); } assertNotNull(response); assertNotNull(response.getOutput().getImageData()); numCIDs = (cids == null) ? 0 : cids.size(); assertTrue("Expected zero attachments but there were:" + numCIDs, numCIDs == 0); }
79. MtomSampleTests#testSendImage_MTOMDisable()
Project: axis2-java
File: MtomSampleTests.java
File: MtomSampleTests.java
/* * Enable attachment Optimization but call an endpoint with @MTOM(enable=false) */ public void testSendImage_MTOMDisable() throws Exception { TestLogger.logger.debug("----------------------------------"); TestLogger.logger.debug("test: " + getName()); String imageResourceDir = IMAGE_DIR; //Create a DataSource from an image File file = new File(imageResourceDir + File.separator + "test.jpg"); ImageInputStream fiis = new FileImageInputStream(file); Image image = ImageIO.read(fiis); DataSource imageDS = new DataSourceImpl("image/jpeg", "test.jpg", image); //Create a DataHandler with the String DataSource object DataHandler dataHandler = new DataHandler(imageDS); //Store the data handler in ImageDepot bean ImageDepot imageDepot = new ObjectFactory().createImageDepot(); imageDepot.setImageData(dataHandler); SendImage request = new ObjectFactory().createSendImage(); request.setInput(imageDepot); //Create the necessary JAXBContext JAXBContext jbc = JAXBContext.newInstance("org.test.mtom"); MTOMFeature mtom21 = new MTOMFeature(); // Create the JAX-WS client needed to send the request Service service = Service.create(QNAME_SERVICE); service.addPort(QNAME_PORT, SOAPBinding.SOAP11HTTP_BINDING, URL_ENDPOINT_MTOMDISABLE); Dispatch<Object> dispatch = service.createDispatch(QNAME_PORT, jbc, Mode.PAYLOAD, mtom21); List cids = null; SendImageResponse response = null; try { JAXBAttachmentUnmarshallerMonitor.setMonitoring(true); response = (SendImageResponse) dispatch.invoke(request); // The cids are collected in the monitor. We will check // this to make sure the response mtom is not inlined cids = JAXBAttachmentUnmarshallerMonitor.getBlobCIDs(); } finally { JAXBAttachmentUnmarshallerMonitor.setMonitoring(false); } assertNotNull(response); assertNotNull(response.getOutput().getImageData()); int numCIDs = (cids == null) ? 0 : cids.size(); assertTrue("Expected zero attachments but there were:" + numCIDs, numCIDs == 0); // Repeat to verify behavior response = null; try { JAXBAttachmentUnmarshallerMonitor.setMonitoring(true); response = (SendImageResponse) dispatch.invoke(request); // The cids are collected in the monitor. We will check // this to make sure the response mtom is not inlined cids = JAXBAttachmentUnmarshallerMonitor.getBlobCIDs(); } finally { JAXBAttachmentUnmarshallerMonitor.setMonitoring(false); } assertNotNull(response); assertNotNull(response.getOutput().getImageData()); numCIDs = (cids == null) ? 0 : cids.size(); assertTrue("Expected zero attachments but there were:" + numCIDs, numCIDs == 0); }
80. MtomSampleTests#testSendImageFeature11()
Project: axis2-java
File: MtomSampleTests.java
File: MtomSampleTests.java
/* * Enable attachment Optimization through the MTOMFeature * Using SOAP11 */ public void testSendImageFeature11() throws Exception { TestLogger.logger.debug("----------------------------------"); TestLogger.logger.debug("test: " + getName()); String imageResourceDir = IMAGE_DIR; //Create a DataSource from an image File file = new File(imageResourceDir + File.separator + "test.jpg"); ImageInputStream fiis = new FileImageInputStream(file); Image image = ImageIO.read(fiis); DataSource imageDS = new DataSourceImpl("image/jpeg", "test.jpg", image); //Create a DataHandler with the String DataSource object DataHandler dataHandler = new DataHandler(imageDS); //Store the data handler in ImageDepot bean ImageDepot imageDepot = new ObjectFactory().createImageDepot(); imageDepot.setImageData(dataHandler); SendImage request = new ObjectFactory().createSendImage(); request.setInput(imageDepot); //Create the necessary JAXBContext JAXBContext jbc = JAXBContext.newInstance("org.test.mtom"); MTOMFeature mtom21 = new MTOMFeature(); // Create the JAX-WS client needed to send the request Service service = Service.create(QNAME_SERVICE); service.addPort(QNAME_PORT, SOAPBinding.SOAP11HTTP_BINDING, URL_ENDPOINT); Dispatch<Object> dispatch = service.createDispatch(QNAME_PORT, jbc, Mode.PAYLOAD, mtom21); List cids = null; SendImageResponse response = null; try { JAXBAttachmentUnmarshallerMonitor.setMonitoring(true); response = (SendImageResponse) dispatch.invoke(request); // The cids are collected in the monitor. We will check // this to make sure the response mtom is not inlined cids = JAXBAttachmentUnmarshallerMonitor.getBlobCIDs(); } finally { JAXBAttachmentUnmarshallerMonitor.setMonitoring(false); } assertNotNull(response); assertNotNull(response.getOutput().getImageData()); int numCIDs = (cids == null) ? 0 : cids.size(); assertTrue("Expected one attachment but there were:" + numCIDs, numCIDs == 1); // Repeat to verify behavior response = null; try { JAXBAttachmentUnmarshallerMonitor.setMonitoring(true); response = (SendImageResponse) dispatch.invoke(request); // The cids are collected in the monitor. We will check // this to make sure the response mtom is not inlined cids = JAXBAttachmentUnmarshallerMonitor.getBlobCIDs(); } finally { JAXBAttachmentUnmarshallerMonitor.setMonitoring(false); } assertNotNull(response); assertNotNull(response.getOutput().getImageData()); numCIDs = (cids == null) ? 0 : cids.size(); assertTrue("Expected one attachment but there were:" + numCIDs, numCIDs == 1); }
81. MtomSampleTests#testSendImageAttachmentAPI11()
Project: axis2-java
File: MtomSampleTests.java
File: MtomSampleTests.java
/* * Enable attachment Optimization through the SOAPBinding method * -- setMTOMEnabled([true|false]) * Using SOAP11 */ public void testSendImageAttachmentAPI11() throws Exception { TestLogger.logger.debug("----------------------------------"); TestLogger.logger.debug("test: " + getName()); String imageResourceDir = IMAGE_DIR; //Create a DataSource from an image File file = new File(imageResourceDir + File.separator + "test.jpg"); ImageInputStream fiis = new FileImageInputStream(file); Image image = ImageIO.read(fiis); DataSource imageDS = new DataSourceImpl("image/jpeg", "test.jpg", image); //Create a DataHandler with the String DataSource object DataHandler dataHandler = new DataHandler(imageDS); //Store the data handler in ImageDepot bean ImageDepot imageDepot = new ObjectFactory().createImageDepot(); imageDepot.setImageData(dataHandler); SendImage request = new ObjectFactory().createSendImage(); request.setInput(imageDepot); //Create the necessary JAXBContext JAXBContext jbc = JAXBContext.newInstance("org.test.mtom"); // Create the JAX-WS client needed to send the request Service service = Service.create(QNAME_SERVICE); service.addPort(QNAME_PORT, SOAPBinding.SOAP11HTTP_BINDING, URL_ENDPOINT); Dispatch<Object> dispatch = service.createDispatch(QNAME_PORT, jbc, Mode.PAYLOAD); //Enable attachment optimization SOAPBinding binding = (SOAPBinding) dispatch.getBinding(); binding.setMTOMEnabled(true); SendImageResponse response = (SendImageResponse) dispatch.invoke(request); assertNotNull(response); assertNotNull(response.getOutput().getImageData()); // Repeat to verify behavior response = (SendImageResponse) dispatch.invoke(request); assertNotNull(response); assertNotNull(response.getOutput().getImageData()); }
82. ThumbnailViewNode#getIcon()
Project: autopsy
File: ThumbnailViewNode.java
File: ThumbnailViewNode.java
@Override @NbBundle.Messages({ "# {0} - file name", "ThumbnailViewNode.progressHandle.text=Generating thumbnail for {0}" }) public Image getIcon(int type) { Image icon = null; if (iconCache != null) { icon = iconCache.get(); } if (icon != null) { return icon; } else { final Content content = this.getLookup().lookup(Content.class); if (content == null) { return ImageUtils.getDefaultThumbnail(); } if (swingWorker == null || swingWorker.isDone()) { swingWorker = new SwingWorker<Image, Object>() { private final ProgressHandle progressHandle = ProgressHandle.createHandle(Bundle.ThumbnailViewNode_progressHandle_text(content.getName())); @Override protected Image doInBackground() throws Exception { progressHandle.start(); return ImageUtils.getThumbnail(content, iconSize); } @Override protected void done() { super.done(); try { iconCache = new SoftReference<>(super.get()); fireIconChange(); } catch (InterruptedExceptionExecutionException | ex) { Logger.getLogger(ThumbnailViewNode.class.getName()).log(Level.SEVERE, "Error getting thumbnail icon for " + content.getName(), ex); } finally { progressHandle.finish(); if (timer != null) { timer.stop(); timer = null; } swingWorker = null; } } }; swingWorker.execute(); } if (timer == null) { timer = new Timer(100, (ActionEvent e) -> { fireIconChange(); }); timer.start(); } return waitingIcon; } }
83. AnimatedGifEncoder#finish()
Project: asciimg
File: AnimatedGifEncoder.java
File: AnimatedGifEncoder.java
/** * Flushes any pending data and closes output file. * If writing to an OutputStream, the stream is not * closed. */ public boolean finish() { if (!started) return false; boolean ok = true; started = false; try { // gif trailer out.write(0x3b); out.flush(); if (closeStream) { out.close(); } } catch (IOException e) { ok = false; } // reset for subsequent use transIndex = 0; out = null; image = null; pixels = null; indexedPixels = null; colorTab = null; closeStream = false; firstFrame = true; return ok; }
84. ImageUtils#resizeImage()
Project: AndroidDrawableFactory
File: ImageUtils.java
File: ImageUtils.java
public static Image resizeImage(BufferedImage bImg, int newWidth, int newHeight) throws FileNotFoundException, IOException { double ratio = getAspectRatio(bImg, newWidth, newHeight); newWidth = (int) (bImg.getWidth(null) * ratio); newHeight = (int) (bImg.getHeight(null) * ratio); Image resizedImage = bImg.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH); return resizedImage; }
85. SwingUtil#createImage()
Project: airavata
File: SwingUtil.java
File: SwingUtil.java
/** * Creates an image from an image contained in the "images" directory. * * @param filename * @return the Image created */ public static Image createImage(String filename) { Image icon = null; URL imgURL = getImageURL(filename); if (imgURL != null) { icon = Toolkit.getDefaultToolkit().getImage(imgURL); } return icon; }
86. JmfDevice#getImage()
Project: webcam-capture
File: JmfDevice.java
File: JmfDevice.java
@Override public BufferedImage getImage() { if (!open) { throw new RuntimeException("Webcam has to be open to get image"); } Buffer buffer = grabber.grabFrame(); Image image = converter.createImage(buffer); if (image == null) { throw new RuntimeException("Cannot get image"); } int width = image.getWidth(null); int height = image.getHeight(null); int type = BufferedImage.TYPE_INT_RGB; BufferedImage buffered = new BufferedImage(width, height, type); Graphics2D g2 = buffered.createGraphics(); g2.drawImage(image, null, null); g2.dispose(); buffered.flush(); return buffered; }
87. ResourcesTest#testImageNotFound()
Project: tomighty
File: ResourcesTest.java
File: ResourcesTest.java
@Test public void testImageNotFound() { Image image = resources.image("/foo.png"); assertThat(image, is(nullValue())); }
88. ResourcesTest#testImage()
Project: tomighty
File: ResourcesTest.java
File: ResourcesTest.java
@Test public void testImage() { Image image = resources.image("/image.png"); assertThat(image, is(notNullValue())); }
89. InitialState#createContent()
Project: tomighty
File: InitialState.java
File: InitialState.java
@Override protected Component createContent() { Image image = images.tomato(); ImageIcon imageIcon = new ImageIcon(image); return new JLabel(imageIcon); }
90. TrayIcons#tomato()
Project: tomighty
File: TrayIcons.java
File: TrayIcons.java
public Image tomato() { int size = tray.iconSize().height; Image image = tomato(size); if (image == null) { image = tomato(DEFAULT_ICON_SIZE); } return image; }
91. Console#showWindow()
Project: ThriftyPaxos
File: Console.java
File: Console.java
private void showWindow() { if (frame != null) { return; } frame = new Frame("H2 Console"); frame.addWindowListener(this); Image image = loadImage("/org/h2/res/h2.png"); if (image != null) { frame.setIconImage(image); } frame.setResizable(false); frame.setBackground(SystemColor.control); GridBagLayout layout = new GridBagLayout(); frame.setLayout(layout); // the main panel keeps everything together Panel mainPanel = new Panel(layout); GridBagConstraints constraintsPanel = new GridBagConstraints(); constraintsPanel.gridx = 0; constraintsPanel.weightx = 1.0D; constraintsPanel.weighty = 1.0D; constraintsPanel.fill = GridBagConstraints.BOTH; constraintsPanel.insets = new Insets(0, 10, 0, 10); constraintsPanel.gridy = 0; GridBagConstraints constraintsButton = new GridBagConstraints(); constraintsButton.gridx = 0; constraintsButton.gridwidth = 2; constraintsButton.insets = new Insets(10, 0, 0, 0); constraintsButton.gridy = 1; constraintsButton.anchor = GridBagConstraints.EAST; GridBagConstraints constraintsTextField = new GridBagConstraints(); constraintsTextField.fill = GridBagConstraints.HORIZONTAL; constraintsTextField.gridy = 0; constraintsTextField.weightx = 1.0; constraintsTextField.insets = new Insets(0, 5, 0, 0); constraintsTextField.gridx = 1; GridBagConstraints constraintsLabel = new GridBagConstraints(); constraintsLabel.gridx = 0; constraintsLabel.gridy = 0; Label label = new Label("H2 Console URL:", Label.LEFT); label.setFont(font); mainPanel.add(label, constraintsLabel); urlText = new TextField(); urlText.setEditable(false); urlText.setFont(font); urlText.setText(web.getURL()); if (isWindows) { urlText.setFocusable(false); } mainPanel.add(urlText, constraintsTextField); startBrowser = new Button("Start Browser"); startBrowser.setFocusable(false); startBrowser.setActionCommand("console"); startBrowser.addActionListener(this); startBrowser.setFont(font); mainPanel.add(startBrowser, constraintsButton); frame.add(mainPanel, constraintsPanel); int width = 300, height = 120; frame.setSize(width, height); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); frame.setLocation((screenSize.width - width) / 2, (screenSize.height - height) / 2); try { frame.setVisible(true); } catch (Throwable t) { } try { // ensure this window is in front of the browser frame.setAlwaysOnTop(true); frame.setAlwaysOnTop(false); } catch (Throwable t) { } }
92. ImageManager#getCroppedExportImage()
Project: SproutLife
File: ImageManager.java
File: ImageManager.java
public BufferedImage getCroppedExportImage(int imageWidth, int imageHeight) { Image logoImage = getLogoImage(imageWidth, imageHeight); BufferedImage image = generateCenteredImage(imageWidth, imageHeight, panelController.getScrollController().getCenterDrawPosition(), logoImage); return image; }
93. ImageManager#getScaledExportImage()
Project: SproutLife
File: ImageManager.java
File: ImageManager.java
public BufferedImage getScaledExportImage(int imageWidth, int imageHeight) { Image logoImage = getLogoImage(imageWidth, imageHeight); BufferedImage scaledImage = generateImage(imageWidth, imageHeight, logoImage, SAVE_IMAGE_PAD); return scaledImage; }
94. ImageManager#generateCenteredImage()
Project: SproutLife
File: ImageManager.java
File: ImageManager.java
public BufferedImage generateCenteredImage(Rectangle2D.Double bounds) { Image logoImage = getLogoImage(bounds.height, bounds.width); return generateCenteredImage(bounds, logoImage); }
95. ImageManager#generatePdf()
Project: SproutLife
File: ImageManager.java
File: ImageManager.java
public ByteArrayOutputStream generatePdf() { Rectangle2D.Double imageRectangle1 = getPaddedExportImageSize(); Rectangle imageRectangle2 = RendererUtils.getAspectScaledRectangle(imageRectangle1, 1224, 792); Image logoImage = smallLogoImage; int imageWidth = imageRectangle2.width; int imageHeight = imageRectangle2.height; int pad = SAVE_IMAGE_PAD; try { panelController.getInteractionLock().readLock().lock(); if (panelController.getScrollController().getVisibleRectangle().width == 0 || panelController.getScrollController().getVisibleRectangle().height == 0) { return null; } //BufferedImage image = new BufferedImage(imageWidth, imageHeight, // BufferedImage.TYPE_INT_RGB); int actualImageWidth = imageWidth - 2 * pad; int actualImageHeight = imageHeight - 2 * pad; Rectangle2D.Double imageRectangle = panelController.getScrollController().getRendererRectangle(); Rectangle newImageDimension = RendererUtils.getAspectScaledRectangle(imageRectangle, actualImageWidth, actualImageHeight); double xZoomFactor = (newImageDimension.width / imageRectangle.width); double yZoomFactor = (newImageDimension.height / imageRectangle.height); int xOffset = 0, yOffset = 0; if (newImageDimension.width < actualImageWidth) { xOffset = (actualImageWidth - newImageDimension.width) / 2; } if (newImageDimension.height < actualImageHeight) { yOffset = (actualImageHeight - newImageDimension.height) / 2; } AffineTransform transform = new AffineTransform(); transform.translate(pad + xOffset, pad + yOffset); transform.scale(xZoomFactor * panelController.getScrollController().getScalingZoomFactor(), yZoomFactor * panelController.getScrollController().getScalingZoomFactor()); transform.translate(-imageRectangle.getMinX() / panelController.getScrollController().getScalingZoomFactor(), -imageRectangle.getMinY() / panelController.getScrollController().getScalingZoomFactor()); return paintImagePdf(logoImage, imageWidth, imageHeight, transform); } finally { panelController.getInteractionLock().readLock().unlock(); } }
96. ImageManager#getLogoImage()
Project: SproutLife
File: ImageManager.java
File: ImageManager.java
public Image getLogoImage(double w, double h) { Image logoImage = smallLogoImage; if (w > 1024 && h > 768) { logoImage = largeLogoImage; } return logoImage; }
97. BufferedImageConverter#toBufferedImage()
Project: spaceracer3d
File: BufferedImageConverter.java
File: BufferedImageConverter.java
// This method returns a buffered image with the contents of an image public static BufferedImage toBufferedImage(final ImageIcon ic) { // This code ensures that all the pixels in the image are loaded final Image image = ic.getImage(); // Determine if the image has transparent pixels; for this method's // implementation, see e661 Determining If an Image Has Transparent Pixels final boolean hasAlpha = hasAlpha(image); // Create a buffered image with a format that's compatible with the screen BufferedImage bimage = null; final 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 final GraphicsDevice gs = ge.getDefaultScreenDevice(); final GraphicsConfiguration gc = gs.getDefaultConfiguration(); bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency); } catch (final HeadlessException e) { } 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 final Graphics g = bimage.createGraphics(); // Paint the image onto the buffered image g.drawImage(image, 0, 0, null); g.dispose(); return bimage; }
98. MapListCellRenderer#resize()
Project: settlers-remake
File: MapListCellRenderer.java
File: MapListCellRenderer.java
/** * Resize image * * @param img * Source image * @param newW * Width * @param newH * Height * @return Rescaled image */ private static Image resize(BufferedImage img, int newW, int newH) { Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH); BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = dimg.createGraphics(); g2d.drawImage(tmp, 0, 0, null); g2d.dispose(); return dimg; }
99. LabelRenderer#render()
Project: Prefuse
File: LabelRenderer.java
File: LabelRenderer.java
/** * @see prefuse.render.Renderer#render(java.awt.Graphics2D, prefuse.visual.VisualItem) */ public void render(Graphics2D g, VisualItem item) { RectangularShape shape = (RectangularShape) getShape(item); if (shape == null) return; // fill the shape, if requested int type = getRenderType(item); if (type == RENDER_TYPE_FILL || type == RENDER_TYPE_DRAW_AND_FILL) GraphicsLib.paint(g, item, shape, getStroke(item), RENDER_TYPE_FILL); // now render the image and text String text = m_text; Image img = getImage(item); if (text == null && img == null) return; double size = item.getSize(); boolean useInt = 1.5 > Math.max(g.getTransform().getScaleX(), g.getTransform().getScaleY()); double x = shape.getMinX() + size * m_horizBorder; double y = shape.getMinY() + size * m_vertBorder; // render image if (img != null) { double w = size * img.getWidth(null); double h = size * img.getHeight(null); double ix = x, iy = y; // determine one co-ordinate based on the image position switch(m_imagePos) { case Constants.LEFT: x += w + size * m_imageMargin; break; case Constants.RIGHT: ix = shape.getMaxX() - size * m_horizBorder - w; break; case Constants.TOP: y += h + size * m_imageMargin; break; case Constants.BOTTOM: iy = shape.getMaxY() - size * m_vertBorder - h; break; default: throw new IllegalStateException("Unrecognized image alignment setting."); } // determine the other coordinate based on image alignment switch(m_imagePos) { case Constants.LEFT: case Constants.RIGHT: // need to set image y-coordinate switch(m_vImageAlign) { case Constants.TOP: break; case Constants.BOTTOM: iy = shape.getMaxY() - size * m_vertBorder - h; break; case Constants.CENTER: iy = shape.getCenterY() - h / 2; break; } break; case Constants.TOP: case Constants.BOTTOM: // need to set image x-coordinate switch(m_hImageAlign) { case Constants.LEFT: break; case Constants.RIGHT: ix = shape.getMaxX() - size * m_horizBorder - w; break; case Constants.CENTER: ix = shape.getCenterX() - w / 2; break; } break; } if (useInt && size == 1.0) { // if possible, use integer precision // results in faster, flicker-free image rendering g.drawImage(img, (int) ix, (int) iy, null); } else { m_transform.setTransform(size, 0, 0, size, ix, iy); g.drawImage(img, m_transform, null); } } // render text int textColor = item.getTextColor(); if (text != null && ColorLib.alpha(textColor) > 0) { g.setPaint(ColorLib.getColor(textColor)); g.setFont(m_font); FontMetrics fm = DEFAULT_GRAPHICS.getFontMetrics(m_font); // compute available width double tw; switch(m_imagePos) { case Constants.TOP: case Constants.BOTTOM: tw = shape.getWidth() - 2 * size * m_horizBorder; break; default: tw = m_textDim.width; } // compute available height double th; switch(m_imagePos) { case Constants.LEFT: case Constants.RIGHT: th = shape.getHeight() - 2 * size * m_vertBorder; break; default: th = m_textDim.height; } // compute starting y-coordinate y += fm.getAscent(); switch(m_vTextAlign) { case Constants.TOP: break; case Constants.BOTTOM: y += th - m_textDim.height; break; case Constants.CENTER: y += (th - m_textDim.height) / 2; } // render each line of text // the line height int lh = fm.getHeight(); int start = 0, end = text.indexOf(m_delim); for (; end >= 0; y += lh) { drawString(g, fm, text.substring(start, end), useInt, x, y, tw); start = end + 1; end = text.indexOf(m_delim, start); } drawString(g, fm, text.substring(start), useInt, x, y, tw); } // draw border if (type == RENDER_TYPE_DRAW || type == RENDER_TYPE_DRAW_AND_FILL) { GraphicsLib.paint(g, item, shape, getStroke(item), RENDER_TYPE_DRAW); } }
100. LabelRenderer#getRawShape()
Project: Prefuse
File: LabelRenderer.java
File: LabelRenderer.java
/** * @see prefuse.render.AbstractShapeRenderer#getRawShape(prefuse.visual.VisualItem) */ protected Shape getRawShape(VisualItem item) { m_text = getText(item); Image img = getImage(item); double size = item.getSize(); // get image dimensions double iw = 0, ih = 0; if (img != null) { ih = img.getHeight(null); iw = img.getWidth(null); } // get text dimensions int tw = 0, th = 0; if (m_text != null) { m_text = computeTextDimensions(item, m_text, size); th = m_textDim.height; tw = m_textDim.width; } // get bounding box dimensions double w = 0, h = 0; switch(m_imagePos) { case Constants.LEFT: case Constants.RIGHT: w = tw + size * (iw + 2 * m_horizBorder + (tw > 0 && iw > 0 ? m_imageMargin : 0)); h = Math.max(th, size * ih) + size * 2 * m_vertBorder; break; case Constants.TOP: case Constants.BOTTOM: w = Math.max(tw, size * iw) + size * 2 * m_horizBorder; h = th + size * (ih + 2 * m_vertBorder + (th > 0 && ih > 0 ? m_imageMargin : 0)); break; default: throw new IllegalStateException("Unrecognized image alignment setting."); } // get the top-left point, using the current alignment settings getAlignedPoint(m_pt, item, w, h, m_xAlign, m_yAlign); if (m_bbox instanceof RoundRectangle2D) { RoundRectangle2D rr = (RoundRectangle2D) m_bbox; rr.setRoundRect(m_pt.getX(), m_pt.getY(), w, h, size * m_arcWidth, size * m_arcHeight); } else { m_bbox.setFrame(m_pt.getX(), m_pt.getY(), w, h); } return m_bbox; }