Java Code Examples for java.awt.image.BufferedImage#TYPE_INT_RGB

The following examples show how to use java.awt.image.BufferedImage#TYPE_INT_RGB . 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: ScaleTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  BufferedImage image = new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
  Graphics2D g = image.createGraphics();

  g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  g.setPaint(Color.WHITE);
  g.fill(new Rectangle(image.getWidth(), image.getHeight()));
  g.scale(.9, .9);
  g.setPaint(Color.BLACK);
  g.setStroke(new BasicStroke(0.5f));
  g.draw(new Ellipse2D.Double(25, 25, 150, 150));

  // To visually check it
  //ImageIO.write(image, "PNG", new File(args[0]));

  boolean nonWhitePixelFound = false;
  for (int x = 100; x < 200; ++x) {
    if (image.getRGB(x, 90) != Color.WHITE.getRGB()) {
      nonWhitePixelFound = true;
      break;
    }
  }
  if (!nonWhitePixelFound) {
    throw new RuntimeException("A circle is rendered like a 'C' shape.");
  }
}
 
Example 2
Source File: GraphicsUtilities.java    From filthy-rich-clients with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * <p>Returns an array of pixels, stored as integers, from a
 * <code>BufferedImage</code>. The pixels are grabbed from a rectangular
 * area defined by a location and two dimensions. Calling this method on
 * an image of type different from <code>BufferedImage.TYPE_INT_ARGB</code>
 * and <code>BufferedImage.TYPE_INT_RGB</code> will unmanage the image.</p>
 *
 * @param img the source image
 * @param x the x location at which to start grabbing pixels
 * @param y the y location at which to start grabbing pixels
 * @param w the width of the rectangle of pixels to grab
 * @param h the height of the rectangle of pixels to grab
 * @param pixels a pre-allocated array of pixels of size w*h; can be null
 * @return <code>pixels</code> if non-null, a new array of integers
 *   otherwise
 * @throws IllegalArgumentException is <code>pixels</code> is non-null and
 *   of length &lt; w*h
 */
public static int[] getPixels(BufferedImage img,
                              int x, int y, int w, int h, int[] pixels) {
    if (w == 0 || h == 0) {
        return new int[0];
    }

    if (pixels == null) {
        pixels = new int[w * h];
    } else if (pixels.length < w * h) {
        throw new IllegalArgumentException("pixels array must have a length" +
                                           " >= w*h");
    }

    int imageType = img.getType();
    if (imageType == BufferedImage.TYPE_INT_ARGB ||
        imageType == BufferedImage.TYPE_INT_RGB) {
        Raster raster = img.getRaster();
        return (int[]) raster.getDataElements(x, y, w, h, pixels);
    }

    // Unmanages the image
    return img.getRGB(x, y, w, h, pixels, 0, w);
}
 
Example 3
Source File: ScaleTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  BufferedImage image = new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
  Graphics2D g = image.createGraphics();

  g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  g.setPaint(Color.WHITE);
  g.fill(new Rectangle(image.getWidth(), image.getHeight()));
  g.scale(.9, .9);
  g.setPaint(Color.BLACK);
  g.setStroke(new BasicStroke(0.5f));
  g.draw(new Ellipse2D.Double(25, 25, 150, 150));

  // To visually check it
  //ImageIO.write(image, "PNG", new File(args[0]));

  boolean nonWhitePixelFound = false;
  for (int x = 100; x < 200; ++x) {
    if (image.getRGB(x, 90) != Color.WHITE.getRGB()) {
      nonWhitePixelFound = true;
      break;
    }
  }
  if (!nonWhitePixelFound) {
    throw new RuntimeException("A circle is rendered like a 'C' shape.");
  }
}
 
Example 4
Source File: ConcurrentWritingTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
private static BufferedImage createTestImage() {
    int w = 1024;
    int h = 768;

    BufferedImage img = new
        BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = img.createGraphics();
    Color[] colors = { Color.red, Color.green, Color.blue };
    float[] dist = {0.0f, 0.5f, 1.0f };
    Point2D center = new Point2D.Float(0.5f * w, 0.5f * h);

    RadialGradientPaint p =
        new RadialGradientPaint(center, 0.5f * w, dist, colors);
    g.setPaint(p);
    g.fillRect(0, 0, w, h);
    g.dispose();

    return img;
}
 
Example 5
Source File: ScaledCopyArea.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(final String[] args) {
    final BufferedImage bi = new BufferedImage(100, 300,
                                               BufferedImage.TYPE_INT_RGB);
    final Graphics2D g = bi.createGraphics();
    g.scale(2, 2);
    g.setColor(Color.RED);
    g.fillRect(0, 0, 100, 300);
    g.setColor(Color.GREEN);
    g.fillRect(0, 100, 100, 100);
    g.copyArea(0, 100, 100, 100, 0, -100);
    g.dispose();
    for (int x = 0; x < 100; ++x) {
        for (int y = 0; y < 100; ++y) {
            final int actual = bi.getRGB(x, y);
            final int exp = Color.GREEN.getRGB();
            if (actual != exp) {
                System.err.println("Expected:" + Integer.toHexString(exp));
                System.err.println("Actual:" + Integer.toHexString(actual));
                throw new RuntimeException("Test " + "failed");
            }
        }
    }
}
 
Example 6
Source File: ExpressionFigure.java    From biojava with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 *
 * @param fileName
 */
public void savePNG(String fileName) {
	if (fileName.startsWith("null")) {
		return;
	}
	this.fileName = fileName;
	BufferedImage image = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB);
	Graphics2D graphics2D = image.createGraphics();

	this.paint(graphics2D);
	try {
		ImageIO.write(image, "png", new File(fileName));
	} catch (Exception ex) {
		ex.printStackTrace();
	}

}
 
Example 7
Source File: PDColorSpace.java    From sambox with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the (A)RGB equivalent of the given raster, using the given AWT color space to perform the conversion.
 * 
 * @param raster the source raster
 * @param colorSpace the AWT
 * @return an (A)RGB buffered image
 */
protected BufferedImage toRGBImageAWT(WritableRaster raster, ColorSpace colorSpace)
{
    //
    // WARNING: this method is performance sensitive, modify with care!
    //

    // ICC Profile color transforms are only fast when performed using ColorConvertOp
    ColorModel colorModel = new ComponentColorModel(colorSpace, false, false,
            Transparency.OPAQUE, raster.getDataBuffer().getDataType());

    BufferedImage src = new BufferedImage(colorModel, raster, false, null);
    BufferedImage dest = new BufferedImage(raster.getWidth(), raster.getHeight(),
            BufferedImage.TYPE_INT_RGB);
    ColorConvertOp op = new ColorConvertOp(null);
    op.filter(src, dest);
    return dest;
}
 
Example 8
Source File: EffectUtils.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * <p>Returns an array of pixels, stored as integers, from a
 * <code>BufferedImage</code>. The pixels are grabbed from a rectangular
 * area defined by a location and two dimensions. Calling this method on
 * an image of type different from <code>BufferedImage.TYPE_INT_ARGB</code>
 * and <code>BufferedImage.TYPE_INT_RGB</code> will unmanage the image.</p>
 *
 * @param img the source image
 * @param x the x location at which to start grabbing pixels
 * @param y the y location at which to start grabbing pixels
 * @param w the width of the rectangle of pixels to grab
 * @param h the height of the rectangle of pixels to grab
 * @param pixels a pre-allocated array of pixels of size w*h; can be null
 * @return <code>pixels</code> if non-null, a new array of integers
 *   otherwise
 * @throws IllegalArgumentException is <code>pixels</code> is non-null and
 *   of length &lt; w*h
 */
public static int[] getPixels(BufferedImage img,
                              int x, int y, int w, int h, int[] pixels) {
    if (w == 0 || h == 0) {
        return new int[0];
    }

    if (pixels == null) {
        pixels = new int[w * h];
    } else if (pixels.length < w * h) {
        throw new IllegalArgumentException("pixels array must have a length" +
                                           " >= w*h");
    }

    int imageType = img.getType();
    if (imageType == BufferedImage.TYPE_INT_ARGB ||
        imageType == BufferedImage.TYPE_INT_RGB) {
        Raster raster = img.getRaster();
        return (int[]) raster.getDataElements(x, y, w, h, pixels);
    }

    // Unmanages the image
    return img.getRGB(x, y, w, h, pixels, 0, w);
}
 
Example 9
Source File: MultiResolutionImageTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
static void generateImage(int scale) throws Exception {
    BufferedImage image = new BufferedImage(scale * IMAGE_WIDTH, scale * IMAGE_HEIGHT,
            BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();
    g.setColor(scale == 1 ? COLOR_1X : COLOR_2X);
    g.fillRect(0, 0, scale * IMAGE_WIDTH, scale * IMAGE_HEIGHT);
    File file = new File(scale == 1 ? IMAGE_NAME_1X : IMAGE_NAME_2X);
    ImageIO.write(image, "png", file);
}
 
Example 10
Source File: ImageIOHelper.java    From JewelCrawler with GNU General Public License v3.0 5 votes vote down vote up
public static BufferedImage imageToBufferedImage(Image image) {
	BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null),
			BufferedImage.TYPE_INT_RGB);
	Graphics2D g = bufferedImage.createGraphics();
	g.drawImage(image, 0, 0, null);
	return bufferedImage;
}
 
Example 11
Source File: JFIFMarkerSegment.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return an RGB image that is the expansion of the given grayscale
 * image.
 */
private static BufferedImage expandGrayThumb(BufferedImage thumb) {
    BufferedImage ret = new BufferedImage(thumb.getWidth(),
                                          thumb.getHeight(),
                                          BufferedImage.TYPE_INT_RGB);
    Graphics g = ret.getGraphics();
    g.drawImage(thumb, 0, 0, null);
    return ret;
}
 
Example 12
Source File: SwingFXUtils.java    From ShootOFF with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Determine the optimal BufferedImage type to use for the specified
 * {@code fxFormat} allowing for the specified {@code bimg} to be use as a
 * potential default storage space if it is not null and is compatible.
 * 
 * @param fxFormat
 *            the PixelFormat of the source FX Image
 * @param bimg
 *            an optional existing {@code BufferedImage} to be used for
 *            storage if it is compatible, or null
 * @return
 */
private static int getBestBufferedImageType(PixelFormat<?> fxFormat, BufferedImage bimg) {
	if (bimg != null) {
		int bimgType = bimg.getType();

		if (bimgType == BufferedImage.TYPE_INT_ARGB || bimgType == BufferedImage.TYPE_INT_ARGB_PRE) {
			// We will allow the caller to give us a BufferedImage
			// that has an alpha channel, but we might not otherwise
			// construct one ourselves.
			// We will also allow them to choose their own premultiply
			// type which may not match the image.
			// If left to our own devices we might choose a more specific
			// format as indicated by the choices below.
			return bimgType;
		}
	}

	switch (fxFormat.getType()) {
	default:
	case BYTE_BGRA_PRE:
	case INT_ARGB_PRE:
		return BufferedImage.TYPE_INT_ARGB_PRE;

	case BYTE_BGRA:
	case INT_ARGB:
		return BufferedImage.TYPE_INT_ARGB;

	case BYTE_RGB:
		return BufferedImage.TYPE_INT_RGB;

	case BYTE_INDEXED:
		return (fxFormat.isPremultiplied() ? BufferedImage.TYPE_INT_ARGB_PRE : BufferedImage.TYPE_INT_ARGB);
	}
}
 
Example 13
Source File: RenderToCustomBufferTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    final BufferedImage dst_custom = createCustomBuffer();
    final BufferedImage dst_dcm = new BufferedImage(width, height,
            BufferedImage.TYPE_INT_RGB);

    renderTo(dst_custom);
    renderTo(dst_dcm);

    check(dst_custom, dst_dcm);
}
 
Example 14
Source File: XYBarChartTest.java    From ccu-historian 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 15
Source File: UndergroundPocketsLayerExporter.java    From WorldPainter with GNU General Public License v3.0 5 votes vote down vote up
/**
     * Create a coloured preview of the layer.
     */
    public BufferedImage createPreview(int width, int height, ColourScheme colourScheme, Terrain subsurfaceMaterial) {
        init();
        final BufferedImage preview = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        final MixedMaterial material = layer.getMaterial();
        final Terrain terrain = layer.getTerrain();
        final boolean useMaterial = material != null;
        if (threshold <= -0.5f) {
            // Special case: replace every block
            for (int x = 0; x < width; x++) {
                for (int z = 0; z < height; z++) {
                    if (useMaterial) {
                        preview.setRGB(x, height - z - 1, colourScheme.getColour(material.getMaterial(0L, x, 0, z)));
                    } else {
                        preview.setRGB(x, height - z - 1, colourScheme.getColour(terrain.getMaterial(0L, x, 0, z, height - 1)));
                    }
                }
            }
        } else {
            for (int x = 0; x < width; x++) {
                for (int z = 0; z < height; z++) {
                    double dx = x / scale, dz = z / scale;
                    if (noiseGenerator.getPerlinNoise(dx, 0.0, dz) >= threshold) {
                        if (useMaterial) {
                            preview.setRGB(x, height - z - 1, colourScheme.getColour(material.getMaterial(0L, x, 0, z)));
                        } else {
                            preview.setRGB(x, height - z - 1, colourScheme.getColour(terrain.getMaterial(0L, x, 0, z, height - 1)));
                        }
                    } else {
                        preview.setRGB(x, height - z - 1, colourScheme.getColour(subsurfaceMaterial.getMaterial(0L, x, 0, z, height - 1)));
                    }
                }
            }
        }
//        drawLabels(preview, height);
        return preview;
    }
 
Example 16
Source File: Figure.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public int getHeight() {
    if (heightCash == -1) {
        BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setFont(diagram.getFont().deriveFont(Font.BOLD));
        FontMetrics metrics = g.getFontMetrics();
        String nodeText = diagram.getNodeText();
        heightCash = nodeText.split("\n").length * metrics.getHeight() + INSET;
    }
    return heightCash;
}
 
Example 17
Source File: MultiResolutionImageTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
static void testToolkitImageObserver(final Image image) {

        ImageObserver observer = new ImageObserver() {

            @Override
            public boolean imageUpdate(Image img, int infoflags, int x, int y,
                int width, int height) {

                if (img != image) {
                    throw new RuntimeException("Wrong image in observer");
                }

                if ((infoflags & (ImageObserver.ERROR | ImageObserver.ABORT))
                    != 0) {
                    throw new RuntimeException("Error during image loading");
                }

                return (infoflags & ImageObserver.ALLBITS) == 0;

            }
        };

        final BufferedImage bufferedImage2x = new BufferedImage(2 * IMAGE_WIDTH,
            2 * IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2x = (Graphics2D) bufferedImage2x.getGraphics();
        setImageScalingHint(g2x, true);

        g2x.drawImage(image, 0, 0, 2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT, 0, 0,
            IMAGE_WIDTH, IMAGE_HEIGHT, observer);

    }
 
Example 18
Source File: JScreenshotViewer.java    From ScreenshotMaker with Apache License 2.0 5 votes vote down vote up
public void toFile(File file) {
    BufferedImage image = new BufferedImage((exportHeight * 9) / 16, exportHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics = image.createGraphics();
    paintScreenshot(graphics, exportHeight);

    try {
        if (ImageIO.write(image, "png", file)) {
            System.out.println("-- saved to " + file.getAbsolutePath());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 19
Source File: VerifyCodeUtil.java    From spring-security with Apache License 2.0 4 votes vote down vote up
public static Map<String, Object> getVerifyCode(){
    Map<String, Object> result = new HashMap<>();
    //width-4 除去左右多余的位置,使验证码更加集中显示,减得越多越集中。
    //codeCount+1     //等比分配显示的宽度,包括左右两边的空格
    codeX = (width-4) / (codeCount+1);
    //height - 10 集中显示验证码
    fontHeight = height - 10;
    codeY = height - 7;
    // 定义图像buffer
    BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D gd = buffImg.createGraphics();
    // 创建一个随机数生成器类
    Random random = new Random();
    // 将图像填充为白色
    gd.setColor(Color.WHITE);
    gd.fillRect(0, 0, width, height);
    // 创建字体,字体的大小应该根据图片的高度来定。
    Font font = new Font("Times New Roman", Font.PLAIN, fontHeight);
    // 设置字体。
    gd.setFont(font);
    // 画边框。
    gd.setColor(Color.BLACK);
    gd.drawRect(0, 0, width - 1, height - 1);
    // 随机产生16条干扰线,使图象中的认证码不易被其它程序探测到。
    gd.setColor(Color.gray);
    for (int i = 0; i < interLine; i++) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(12);
        int yl = random.nextInt(12);
        gd.drawLine(x, y, x + xl, y + yl);
    }
    // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
    StringBuffer randomCode = new StringBuffer();
    int red = 0, green = 0, blue = 0;
    // 随机产生codeCount数字的验证码。
    for (int i = 0; i < codeCount; i++) {
        // 得到随机产生的验证码数字。
        String strRand = String.valueOf(codeSequence[random.nextInt(36)]);
        // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。
        red = random.nextInt(255);
        green = random.nextInt(255);
        blue = random.nextInt(255);
        // 用随机产生的颜色将验证码绘制到图像中。
        gd.setColor(new Color(red,green,blue));
        gd.drawString(strRand, (i + 1) * codeX, codeY);
        // 将产生的四个随机数组合在一起。
        randomCode.append(strRand);
    }
    result.put(BUFFIMG_KEY, buffImg);
    result.put(SESSION_KEY, randomCode.toString());
    return result;
}
 
Example 20
Source File: GraphicsUtilities.java    From orbit-image-analysis with GNU General Public License v3.0 4 votes vote down vote up
/**
 * <p>
 * Writes a rectangular area of pixels in the destination <code>BufferedImage</code>. Calling this
 * method on an image of type different from <code>BufferedImage.TYPE_INT_ARGB</code> and
 * <code>BufferedImage.TYPE_INT_RGB</code> will unmanage the image.
 * </p>
 *
 * @param img
 *          the destination image
 * @param x
 *          the x location at which to start storing pixels
 * @param y
 *          the y location at which to start storing pixels
 * @param w
 *          the width of the rectangle of pixels to store
 * @param h
 *          the height of the rectangle of pixels to store
 * @param pixels
 *          an array of pixels, stored as integers
 * @throws IllegalArgumentException
 *           is <code>pixels</code> is non-null and of length &lt; w*h
 */
public static void setPixels(BufferedImage img, int x, int y, int w, int h, int[] pixels) {
  if (pixels == null || w == 0 || h == 0) {
    return;
  } else if (pixels.length < w * h) {
    throw new IllegalArgumentException("pixels array must have a length" + " >= w*h");
  }

  int imageType = img.getType();
  if (imageType == BufferedImage.TYPE_INT_ARGB || imageType == BufferedImage.TYPE_INT_RGB) {
    WritableRaster raster = img.getRaster();
    raster.setDataElements(x, y, w, h, pixels);
  } else {
    // Unmanages the image
    img.setRGB(x, y, w, h, pixels, 0, w);
  }
}