Java Code Examples for java.awt.image.BufferedImage#createGraphics()

The following examples show how to use java.awt.image.BufferedImage#createGraphics() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SamePackingTypeTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void doTest(BufferedImageOp op, int stype, int dtype) {
    final int size = 100;

    final BufferedImage src = new BufferedImage(size, size, stype);
    Graphics2D g = src.createGraphics();
    g.setColor(Color.red);
    g.fillRect(0, 0, size, size);
    g.dispose();


    final BufferedImage dst = new BufferedImage(size, size, dtype);
    g = dst.createGraphics();
    g.setColor(Color.blue);
    g.fillRect(0, 0, size, size);
    g.dispose();

    op.filter(src, dst);

    final int rgb = dst.getRGB(size - 1, size - 1);
    System.out.printf("dst: 0x%X ", rgb);

    if (rgb != 0xFFFF0000) {
        throw new RuntimeException(String.format("Wrong color in dst: 0x%X", rgb));
    }
}
 
Example 2
Source File: ImageUtil.java    From imageServer with Apache License 2.0 6 votes vote down vote up
/**
 * 调整图像透明度
 *
 * @param image
 * @param alpha
 */
public void getImageAlpha(BufferedImage image, float alpha) {
    if(alpha != 1){
        BufferedImage bufferedImage = new BufferedImage(image.getWidth(), image.getHeight(),
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bufferedImage.createGraphics();
        bufferedImage = g2.getDeviceConfiguration().createCompatibleImage(image.getWidth(), image.getHeight(), Transparency.TRANSLUCENT);
        g2.dispose();
        g2 = bufferedImage.createGraphics();
        g2.setComposite(AlphaComposite.SrcOver.derive(alpha));
        g2.drawImage(
                image.getScaledInstance(image.getWidth(), image.getHeight(), Image.SCALE_SMOOTH),
                0, 0, null);

        g2.dispose();
    }
}
 
Example 3
Source File: IncorrectClipSurface2SW.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void draw(Shape clip, Shape to, Image vi, BufferedImage bi,
                         int scale) {
    Graphics2D big = bi.createGraphics();
    big.setComposite(AlphaComposite.Src);
    big.setClip(clip);
    Rectangle toBounds = to.getBounds();
    int x1 = toBounds.x;

    int y1 = toBounds.y;
    int x2 = x1 + toBounds.width;
    int y2 = y1 + toBounds.height;
    big.drawImage(vi, x1, y1, x2, y2, 0, 0, toBounds.width / scale,
                  toBounds.height / scale, null);
    big.dispose();
    vi.flush();
}
 
Example 4
Source File: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
public static TexturePaint createCheckerTexture(int cs, Color color) {
  int size = cs * cs;
  BufferedImage img = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
  Graphics2D g2 = img.createGraphics();
  g2.setPaint(color);
  g2.fillRect(0, 0, size, size);
  for (int i = 0; i * cs < size; i++) {
    for (int j = 0; j * cs < size; j++) {
      if ((i + j) % 2 == 0) {
        g2.fillRect(i * cs, j * cs, cs, cs);
      }
    }
  }
  g2.dispose();
  return new TexturePaint(img, new Rectangle(size, size));
}
 
Example 5
Source File: LogExtractor.java    From rcrs-server with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public BufferedImage paintImage() {
    if (viewers.isEmpty()) {
        return null;
    }
    ViewComponent view = viewers.get(0);
    view.view(current_model, null, null);
    //Create the image
    GraphicsConfiguration configuration = GraphicsEnvironment.getLocalGraphicsEnvironment()
    .getDefaultScreenDevice().getDefaultConfiguration();
    BufferedImage image = configuration.createCompatibleImage(view.getWidth(), view.getHeight(), Transparency.TRANSLUCENT);
        
    //Render the component onto the image
    Graphics graphics = image.createGraphics();
    view.paint(graphics);
    graphics.dispose();
    return image;
}
 
Example 6
Source File: ImageUtils.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
static BufferedImage resize(BufferedImage image, int width, int height) {
    final BufferedImage resized = new BufferedImage(width, 64, image.getType());
    final Graphics2D g = resized.createGraphics();
    g.addRenderingHints(ImmutableMap.of(RenderingHints.KEY_INTERPOLATION,
                                        RenderingHints.VALUE_INTERPOLATION_BILINEAR));
    g.drawImage(image, 0, 0, width, height, null);
    g.dispose();
    return resized;
}
 
Example 7
Source File: MTransferableLabel.java    From javamelody with Apache License 2.0 5 votes vote down vote up
private BufferedImage convertImageIconToBufferedImage(ImageIcon icon) {
	final int type = BufferedImage.TYPE_INT_ARGB;
	final int width = icon.getIconWidth();
	final int height = icon.getIconHeight();
	final BufferedImage scratchImage = new BufferedImage(width, height, type);
	final Graphics2D g2 = scratchImage.createGraphics();
	g2.drawImage(icon.getImage(), 0, 0, null);
	g2.dispose();
	return scratchImage;
}
 
Example 8
Source File: IncorrectClipXorModeSurface2Surface.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private static BufferedImage getSourceGold(GraphicsConfiguration gc,
                                           int size) {
    final BufferedImage bi = gc.createCompatibleImage(size, size);
    Graphics2D g2d = bi.createGraphics();
    g2d.setColor(Color.RED);
    g2d.fillRect(0, 0, size, size);
    g2d.dispose();
    return bi;
}
 
Example 9
Source File: XYStepChartTest.java    From openstock with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Draws the chart with a null info object to make sure that no exceptions
 * are thrown (a problem that was occurring at one point).
 */
@Test
public void testDrawWithNullInfo() {
    try {
        BufferedImage image = new BufferedImage(200 , 100,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        this.chart.draw(g2, new Rectangle2D.Double(0, 0, 200, 100), null,
                null);
        g2.dispose();
    }
    catch (Exception e) {
      fail("No exception should be triggered.");
    }
}
 
Example 10
Source File: AwtRenderingBackend.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 * @param imageWidth the width
 * @param imageHeight the height
 */
public AwtRenderingBackend(final int imageWidth, final int imageHeight) {
    id_ = ID_GENERATOR_++;
    if (LOG.isDebugEnabled()) {
        LOG.debug("[" + id_ + "] AwtRenderingBackend(" + imageWidth + ", " + imageHeight + ")");
    }

    image_ = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
    graphics2D_ = image_.createGraphics();

    graphics2D_.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    graphics2D_.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    graphics2D_.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    // reset
    fillColor_ = Color.black;
    strokeColor_ = Color.black;
    lineWidth_ = 1;
    transformation_ = new AffineTransform();
    setGlobalAlpha(1.0);
    graphics2D_.setClip(null);

    graphics2D_.setBackground(new Color(0f, 0f, 0f, 0f));
    graphics2D_.setColor(Color.black);
    graphics2D_.clearRect(0, 0, imageWidth, imageHeight);

    subPaths_ = new ArrayList<>();
    savedStates_ = new ArrayDeque<>();
}
 
Example 11
Source File: PSPrinterJob.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Examine the metrics captured by the
 * <code>PeekGraphics</code> instance and
 * if capable of directly converting this
 * print job to the printer's control language
 * or the native OS's graphics primitives, then
 * return a <code>PSPathGraphics</code> to perform
 * that conversion. If there is not an object
 * capable of the conversion then return
 * <code>null</code>. Returning <code>null</code>
 * causes the print job to be rasterized.
 */

protected Graphics2D createPathGraphics(PeekGraphics peekGraphics,
                                        PrinterJob printerJob,
                                        Printable painter,
                                        PageFormat pageFormat,
                                        int pageIndex) {

    PSPathGraphics pathGraphics;
    PeekMetrics metrics = peekGraphics.getMetrics();

    /* If the application has drawn anything that
     * out PathGraphics class can not handle then
     * return a null PathGraphics.
     */
    if (forcePDL == false && (forceRaster == true
                    || metrics.hasNonSolidColors()
                    || metrics.hasCompositing())) {

        pathGraphics = null;
    } else {

        BufferedImage bufferedImage = new BufferedImage(8, 8,
                                        BufferedImage.TYPE_INT_RGB);
        Graphics2D bufferedGraphics = bufferedImage.createGraphics();
        boolean canRedraw = peekGraphics.getAWTDrawingOnly() == false;

        pathGraphics =  new PSPathGraphics(bufferedGraphics, printerJob,
                                           painter, pageFormat, pageIndex,
                                           canRedraw);
    }

    return pathGraphics;
}
 
Example 12
Source File: JpegWriterLeakTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static BufferedImage getImage() {
    int width = 2500;
    int height = new Random().nextInt(2500) + 1;
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    Graphics2D g = image.createGraphics();
    g.setColor(Color.blue);
    g.fillRect(0, 0, width, height);

    return image;
}
 
Example 13
Source File: BitDepth.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private File testWriteRGB(String format, int type)
    throws IOException {
    BufferedImage bi = new BufferedImage(width, height, type);
    Graphics2D g = bi.createGraphics();

    Color white = new Color(255, 255, 255);
    Color red = new Color(255, 0, 0);
    Color green = new Color(0, 255, 0);
    Color blue = new Color(0, 0, 255);

    g.setColor(white);
    g.fillRect(0, 0, width, height);
    g.setColor(red);
    g.fillRect(10, 10, 20, 20);
    g.setColor(green);
    g.fillRect(30, 30, 20, 20);
    g.setColor(blue);
    g.fillRect(50, 50, 20, 20);

    File file = new File("BitDepth_" + biTypeNames[type] + "." + format);
    try {
        ImageIO.write(bi, format, file);
    } catch (RuntimeException re) {
        System.out.println("Can't write a type "
                           + biTypeNames[type] +
                           " BufferedImage!");
    }

    return file;
}
 
Example 14
Source File: CTrayIcon.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Scales an icon using specified scale factor
 *
 * @param icon        icon to scale
 * @param scaleFactor scale factor to use
 * @return scaled icon as BuffedredImage
 */
private static BufferedImage scaleIcon(Icon icon, double scaleFactor) {
    if (icon == null) {
        return null;
    }

    int w = icon.getIconWidth();
    int h = icon.getIconHeight();

    GraphicsEnvironment ge =
            GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gd = ge.getDefaultScreenDevice();
    GraphicsConfiguration gc = gd.getDefaultConfiguration();

    // convert icon into image
    BufferedImage iconImage = gc.createCompatibleImage(w, h,
            Transparency.TRANSLUCENT);
    Graphics2D g = iconImage.createGraphics();
    icon.paintIcon(null, g, 0, 0);
    g.dispose();

    // and scale it nicely
    int scaledW = (int) (w * scaleFactor);
    int scaledH = (int) (h * scaleFactor);
    BufferedImage scaledImage = gc.createCompatibleImage(scaledW, scaledH,
            Transparency.TRANSLUCENT);
    g = scaledImage.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.drawImage(iconImage, 0, 0, scaledW, scaledH, null);
    g.dispose();

    return scaledImage;
}
 
Example 15
Source File: Compiler.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
private BufferedImage produceForegroundImageIcon(BufferedImage icon) {
  int imageWidth = icon.getWidth();
  // According to the adaptive icon documentation, both layers are 108x108dp but only the inner
  // 72x72dp appears in the masked viewport, so we shrink down the size of the image accordingly.
  double iconWidth = imageWidth * 72.0 / 108.0;
  // Round iconWidth value to even int for a centered png
  int intIconWidth = ((int)Math.round(iconWidth / 2) * 2);
  Image tmp = icon.getScaledInstance(intIconWidth, intIconWidth, Image.SCALE_SMOOTH);
  int marginWidth = ((imageWidth - intIconWidth) / 2);
  BufferedImage foregroundImageIcon = new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_ARGB);
  Graphics2D g2 = foregroundImageIcon.createGraphics();
  g2.drawImage(tmp, marginWidth, marginWidth, null);
  return foregroundImageIcon;
}
 
Example 16
Source File: ITXtTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static BufferedImage createBufferedImage() {
    BufferedImage image = new BufferedImage(128, 128,
                  BufferedImage.TYPE_4BYTE_ABGR_PRE);
    Graphics2D graph = image.createGraphics();
    graph.setPaintMode();
    graph.setColor(Color.orange);
    graph.fillRect(32, 32, 64, 64);
    graph.dispose();
    return image;
}
 
Example 17
Source File: EditableDisplayerTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static final BufferedImage toBufferedImage(Image img) {
    // load the image
    new ImageIcon(img);
    BufferedImage rep = createBufferedImage(img.getWidth(null), img.getHeight(null));
    Graphics g = rep.createGraphics();
    g.drawImage(img, 0, 0, null);
    g.dispose();
    img.flush();
    return rep;
}
 
Example 18
Source File: DestTypeTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static BufferedImage createTestImage(int type) {
    int w = 100;
    int h = 500;
    BufferedImage bi = new BufferedImage(3*w, h, type);
    Graphics g = bi.createGraphics();
    g.setColor(Color.red);
    g.fillRect(0,0,w,h);
    g.setColor(Color.green);
    g.fillRect(w, 0,w,h);
    g.setColor(Color.blue);
    g.fillRect(2*w,0,w,h);

    return bi;
}
 
Example 19
Source File: GraphicsUtilities.java    From filthy-rich-clients with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * <p>Returns a thumbnail of a source image.</p>
 * <p>This method offers a good trade-off between speed and quality.
 * The result looks better than
 * {@link #createThumbnailFast(java.awt.image.BufferedImage, int)} when
 * the new size is less than half the longest dimension of the source
 * image, yet the rendering speed is almost similar.</p>
 *
 * @see #createThumbnailFast(java.awt.image.BufferedImage, int)
 * @see #createThumbnailFast(java.awt.image.BufferedImage, int, int)
 * @see #createThumbnail(java.awt.image.BufferedImage, int)
 * @param image the source image
 * @param newWidth the width of the thumbnail
 * @param newHeight the height of the thumbnail
 * @return a new compatible <code>BufferedImage</code> containing a
 *   thumbnail of <code>image</code>
 * @throws IllegalArgumentException if <code>newWidth</code> is larger than
 *   the width of <code>image</code> or if code>newHeight</code> is larger
 *   than the height of <code>image or if one the dimensions is not &gt; 0</code>
 */
public static BufferedImage createThumbnail(BufferedImage image,
                                            int newWidth, int newHeight) {
    int width = image.getWidth();
    int height = image.getHeight();

    if (newWidth >= width || newHeight >= height) {
        throw new IllegalArgumentException("newWidth and newHeight cannot" +
                                           " be greater than the image" +
                                           " dimensions");
    } else if (newWidth <= 0 || newHeight <= 0) {
        throw new IllegalArgumentException("newWidth and newHeight must" +
                                           " be greater than 0");
    }

    BufferedImage thumb = image;

    do {
        if (width > newWidth) {
            width /= 2;
            if (width < newWidth) {
                width = newWidth;
            }
        }

        if (height > newHeight) {
            height /= 2;
            if (height < newHeight) {
                height = newHeight;
            }
        }

        BufferedImage temp = createCompatibleImage(image, width, height);
        Graphics2D g2 = temp.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(thumb, 0, 0, temp.getWidth(), temp.getHeight(), null);
        g2.dispose();

        thumb = temp;
    } while (width != newWidth || height != newHeight);

    return thumb;
}
 
Example 20
Source File: GraphicsUtilities.java    From mars-sim with GNU General Public License v3.0 4 votes vote down vote up
/**
 * <p>Returns a thumbnail of a source image. <code>newSize</code> defines
 * the length of the longest dimension of the thumbnail. The other
 * dimension is then computed according to the dimensions ratio of the
 * original picture.</p>
 * <p>This method favors speed over quality. When the new size is less than
 * half the longest dimension of the source image,
 * {@link #createThumbnail(BufferedImage, int)} or
 * {@link #createThumbnail(BufferedImage, int, int)} should be used instead
 * to ensure the quality of the result without sacrificing too much
 * performance.</p>
 *
 * @see #createThumbnailFast(java.awt.image.BufferedImage, int, int)
 * @see #createThumbnail(java.awt.image.BufferedImage, int)
 * @see #createThumbnail(java.awt.image.BufferedImage, int, int)
 * @param image the source image
 * @param newSize the length of the largest dimension of the thumbnail
 * @return a new compatible <code>BufferedImage</code> containing a
 *   thumbnail of <code>image</code>
 * @throws IllegalArgumentException if <code>newSize</code> is larger than
 *   the largest dimension of <code>image</code> or &lt;= 0
 */
public static BufferedImage createThumbnailFast(BufferedImage image,
                                                int newSize) {
    float ratio;
    int width = image.getWidth();
    int height = image.getHeight();

    if (width > height) {
        if (newSize >= width) {
            throw new IllegalArgumentException("newSize must be lower than" +
                                               " the image width");
        } else if (newSize <= 0) {
             throw new IllegalArgumentException("newSize must" +
                                                " be greater than 0");
        }

        ratio = (float) width / (float) height;
        width = newSize;
        height = (int) (newSize / ratio);
    } else {
        if (newSize >= height) {
            throw new IllegalArgumentException("newSize must be lower than" +
                                               " the image height");
        } else if (newSize <= 0) {
             throw new IllegalArgumentException("newSize must" +
                                                " be greater than 0");
        }

        ratio = (float) height / (float) width;
        height = newSize;
        width = (int) (newSize / ratio);
    }

    BufferedImage temp = createCompatibleImage(image, width, height);
    Graphics2D g2 = temp.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                        RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(image, 0, 0, temp.getWidth(), temp.getHeight(), null);
    g2.dispose();

    return temp;
}