Java Code Examples for java.awt.image.BufferedImage

The following examples show how to use java.awt.image.BufferedImage. These examples are extracted from open source projects. 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 Project: hottub   Source File: SunGraphics2D.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void drawImage(BufferedImage bImg,
                      BufferedImageOp op,
                      int x,
                      int y)  {

    if (bImg == null) {
        return;
    }

    try {
        imagepipe.transformImage(this, bImg, op, x, y);
    } catch (InvalidPipeException e) {
        try {
            revalidateAll();
            imagepipe.transformImage(this, bImg, op, x, y);
        } catch (InvalidPipeException e2) {
            // Still catching the exception; we are not yet ready to
            // validate the surfaceData correctly.  Fail for now and
            // try again next time around.
        }
    } finally {
        surfaceData.markDirty();
    }
}
 
Example 2
Source Project: Pixelitor   Source File: PolarTiles.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public BufferedImage doTransform(BufferedImage src, BufferedImage dest) {
    if (filter == null) {
        filter = new PolarTilesFilter();
    }

    filter.setRelCenter(center.getRelativeX(), center.getRelativeY());
    filter.setEdgeAction(edgeAction.getValue());
    filter.setInterpolation(interpolation.getValue());
    filter.setRotateResult((float) rotateImage.getValueInIntuitiveRadians());
    filter.setZoom(zoom.getPercentageValF());
    filter.setT(rotateEffect.getPercentageValF());
    filter.setNumADivisions(numAngDivisions.getValue());
    filter.setNumRDivisions(numRadDivisions.getValue());
    filter.setCurvature(curvature.getValueAsDouble());
    filter.setRandomness(randomness.getPercentageValF());

    dest = filter.filter(src, dest);
    return dest;
}
 
Example 3
Source Project: JImageHash   Source File: CumulativeMatcherTest.java    License: MIT License 6 votes vote down vote up
private void assertImageMatches(CumulativeMatcher matcher) {
	// We only expect ballon to be returned
	final PriorityQueue<Result<BufferedImage>> results = matcher.getMatchingImages(ballon);

	assertAll("Ballon", () -> {
		assertEquals(1, results.size());
	}, () -> {
		assertEquals(ballon, results.peek().value);
	});

	final PriorityQueue<Result<BufferedImage>> results1 = matcher.getMatchingImages(highQuality);

	assertAll("Matches", () -> {
		assertEquals(4, results1.size());
	}, () -> {
		assertFalse(results1.stream().anyMatch(result -> result.value.equals(ballon)));
	});
}
 
Example 4
Source Project: littleluck   Source File: JMandelbrot.java    License: Apache License 2.0 6 votes vote down vote up
private void calcConstants(int width, int height) {
    if ((width >= MIN_WIDTH) && (height >= MIN_HEIGHT)) {
        double oldIntervalWidth = xHighLimit - xLowLimit;
        double oldIntervalHeight = yHighLimit - yLowLimit;
        double newIntervalWidth =
                width * oldIntervalWidth / oldComponentWidth;
        double newIntervalHeight =
                height * oldIntervalHeight / oldComponentHeight;
        double xDiff = newIntervalWidth - oldIntervalWidth;
        double yDiff = newIntervalHeight - oldIntervalHeight;
        xLowLimit -= xDiff / 2;
        xHighLimit += xDiff / 2;
        yLowLimit -= yDiff / 2;
        yHighLimit += yDiff / 2;
        buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        oldComponentWidth = width;
        oldComponentHeight = height;
        setCenter(calcCenter());
    }
}
 
Example 5
public ImageGenerator(int _width, int _height, Color bgColor)
{
      width = _width;
      height = _height;
      bi = new BufferedImage(
          width,
          height,
          BufferedImage.TYPE_INT_ARGB);
      Graphics gr = bi.getGraphics();
      if(null==bgColor){
          bgColor = Color.WHITE;
      }
      gr.setColor(bgColor);
      gr.fillRect(0, 0, width, height);
      paint(gr);
      gr.dispose();
}
 
Example 6
Source Project: MeteoInfo   Source File: CubeTexture.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void init(GLAutoDrawable drawable) {
    final GL2 gl = drawable.getGL().getGL2();
    gl.glShadeModel(GL2.GL_SMOOTH);
    gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
    gl.glClearDepth(1.0f);
    gl.glEnable(GL2.GL_DEPTH_TEST);
    gl.glDepthFunc(GL2.GL_LEQUAL);
    gl.glHint(GL2.GL_PERSPECTIVE_CORRECTION_HINT, GL2.GL_NICEST);
    gl.glEnable(GL2.GL_TEXTURE_2D);
    
    try {
        File im = new File("D:\\Temp\\image\\lenna.jpg ");
        //File im = new File("D:\\Temp\\Map\\GLOBALeb3colshade.jpg");
        BufferedImage image = ImageIO.read(im);
        Texture t = AWTTextureIO.newTexture(gl.getGLProfile(), image, true);
        //Texture t = TextureIO.newTexture(im, true);
        texture = t.getTextureObject(gl);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 7
Source Project: Pixelitor   Source File: JHUnderWater.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public BufferedImage doTransform(BufferedImage src, BufferedImage dest) {
    if (amount.isZero()) {
        return src;
    }
    
    if(filter == null) {
        filter = new SwimFilter(NAME);
    }

    filter.setAmount(amount.getValueAsFloat());
    filter.setScale(scale.getValueAsFloat());
    filter.setStretch((float) Math.pow(10.0, stretch.getValueAsDouble() / 100.0));
    filter.setTime(time.getPercentageValF());
    filter.setAngle((float) (angle.getValueInRadians() + Math.PI / 2.0));
    filter.setEdgeAction(edgeAction.getValue());
    filter.setInterpolation(interpolation.getValue());

    dest = filter.filter(src, dest);
    return dest;
}
 
Example 8
Source Project: jdk8u60   Source File: GraphicsPrimitive.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected static SurfaceData convertFrom(Blit ob, SurfaceData srcData,
                                         int srcX, int srcY, int w, int h,
                                         SurfaceData dstData, int type)
{
    if (dstData != null) {
        Rectangle r = dstData.getBounds();
        if (w > r.width || h > r.height) {
            dstData = null;
        }
    }
    if (dstData == null) {
        BufferedImage dstBI = new BufferedImage(w, h, type);
        dstData = BufImgSurfaceData.createData(dstBI);
    }
    ob.Blit(srcData, dstData, AlphaComposite.Src, null,
            srcX, srcY, 0, 0, w, h);
    return dstData;
}
 
Example 9
Source Project: hifive-pitalium   Source File: PtlWebDriver.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 指定されたリスト内の最後の画像の高さ、スクロール量、ボーダー幅から<br>
 * トリム量を計算し、縦の重複をトリムします。
 *
 * @param images 対象の画像
 * @param lastScrollAmount 最後のスクロール量
 * @param el 撮影対象の要素
 * @param currentScale 表示領域とスクリーンショットのサイズ比
 */
protected void trimBottomImage(List<BufferedImage> images, long lastScrollAmount, PtlWebElement el,
		double currentScale) {
	LOG.trace("(trimBottomImage) lastScrollAmount: {}, el: {}, currentScroll: {}", lastScrollAmount, el,
			currentScale);

	int size = images.size();
	// 画像が1枚しかないときは何もしない
	if (size <= 1) {
		return;
	}

	BufferedImage lastImage = images.get(size - 1);
	int trimTop = calcTrimTop(lastImage.getHeight(), lastScrollAmount, el, currentScale);
	LOG.trace("(trimBottomImage) trim: {}", trimTop);

	if (trimTop > 0 && trimTop < lastImage.getHeight()) {
		images.set(size - 1, ImageUtils.trim(lastImage, trimTop, 0, 0, 0));
	}
}
 
Example 10
Source Project: phoebus   Source File: AWTFontCalibration.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public double getCalibrationFactor()
{
    final BufferedImage buf = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB);
    final Graphics2D gc = buf.createGraphics();
    gc.setFont(font);
    final FontMetrics metrics = gc.getFontMetrics();
    text_width = metrics.stringWidth(FontCalibration.TEXT);
    text_height = metrics.getHeight();
    gc.dispose();

    logger.log(Level.FINE,
               "Font calibration measure: " + text_width + " x " + text_height);
    final double factor = FontCalibration.PIXEL_WIDTH / text_width;
    logger.log(Level.CONFIG, "AWT font calibration factor: {0}", factor);
    return factor;
}
 
Example 11
private static boolean isSameColors(BufferedImage src, BufferedImage dst) {
    Object dstPixel = dst.getRaster().getDataElements(width/2, height/2, null);
    Object srcPixel = src.getRaster().getDataElements(width/2, height/2, null);

    // take into account the rounding error
    if ( Math.abs(src.getColorModel().getRed(srcPixel) -  dst.getColorModel().getRed(dstPixel)) > 1
         || Math.abs(src.getColorModel().getGreen(srcPixel) - dst.getColorModel().getGreen(dstPixel)) > 1
         || Math.abs(src.getColorModel().getBlue(srcPixel) - dst.getColorModel().getBlue(dstPixel)) > 1) {
        showPixel(src, width/2, height/2);
        showPixel(dst, width/2, height/2);

        throw new RuntimeException( "Colors are different: "
                                    + Integer.toHexString(src.getColorModel().getRGB(srcPixel))
                                    + " and "
                                    + Integer.toHexString(dst.getColorModel().getRGB(dstPixel)));
    }
    return true;
}
 
Example 12
Source Project: TencentKona-8   Source File: SurfaceManager.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the SurfaceManager object contained within the given Image.
 */
public static SurfaceManager getManager(Image img) {
    SurfaceManager sMgr = imgaccessor.getSurfaceManager(img);
    if (sMgr == null) {
        /*
         * In practice only a BufferedImage will get here.
         */
        try {
            BufferedImage bi = (BufferedImage) img;
            sMgr = new BufImgSurfaceManager(bi);
            setManager(bi, sMgr);
        } catch (ClassCastException e) {
            throw new IllegalArgumentException("Invalid Image variant");
        }
    }
    return sMgr;
}
 
Example 13
Source Project: MyBox   Source File: ImageGifFile.java    License: Apache License 2.0 6 votes vote down vote up
public static void writeGifImageFile(BufferedImage image,
        ImageAttributes attributes, String outFile) {
    try {
        ImageWriter writer = getWriter();
        ImageWriteParam param = getPara(attributes, writer);
        IIOMetadata metaData = getWriterMeta(attributes, image, writer, param);

        try ( ImageOutputStream out = ImageIO.createImageOutputStream(new File(outFile))) {
            writer.setOutput(out);
            writer.write(metaData, new IIOImage(image, null, metaData), param);
            out.flush();
        }
        writer.dispose();

    } catch (Exception e) {
        logger.error(e.toString());
    }
}
 
Example 14
Source Project: smart-admin   Source File: KaptchaNoise.java    License: MIT License 6 votes vote down vote up
@Override
public void makeNoise(BufferedImage image, float factorOne, float factorTwo, float factorThree, float factorFour) {

    int width = image.getWidth();
    int height = image.getHeight();
    Graphics2D graph = (Graphics2D)image.getGraphics();
    graph.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
    graph.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
    Random random = new Random();
    int noiseLineNum = random.nextInt(3);
    if(noiseLineNum == 0){
        noiseLineNum = 1;
    }
    for (int i = 0; i < noiseLineNum; i++){
        graph.setColor(KaptchaColor.getColor());
        graph.drawLine(random.nextInt(width), random.nextInt(height), 10 + random.nextInt(20), 10 + random.nextInt(20));
    }

    graph.dispose();
}
 
Example 15
Source Project: openjdk-jdk8u   Source File: bug8016833.java    License: GNU General Public License v2.0 6 votes vote down vote up
void testStrikthrough() {
    System.out.println("  testStrikthrough()");

    final BufferedImage img1 = createImage();
    drawText(img1.getGraphics(), false, true, false);
    final Rectangle out1 = getPixelsOutline(img1);
    System.out.println("   Striked: " + out1);

    final BufferedImage img2 = createImage();
    drawText(img2.getGraphics(), false, false, false);
    final Rectangle out2 = getPixelsOutline(img2);
    System.out.println("   Normal: " + out2);

    final BufferedImage img3 = subImages(img1, img2);
    final Rectangle out3 = getPixelsOutline(img3);
    System.out.println("   Sub: " + out3);

    // strikethrough is not too thick
    assertTrue(out3.getHeight() <= 2);
    // not too wide
    assertTrue(out3.getWidth() * 0.8 < out2.getWidth());
    // not too low
    assertTrue(out3.getY() - (out1.getY() + out2.getHeight() - 1) < 0);
    // not too high
    assertTrue(out3.getY() - out1.getY() > 1);
}
 
Example 16
Source Project: openjdk-jdk8u   Source File: Test7019861.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] argv) throws Exception {
    BufferedImage im = getWhiteImage(30, 30);
    Graphics2D g2 = (Graphics2D)im.getGraphics();
    g2.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(KEY_STROKE_CONTROL, VALUE_STROKE_PURE);
    g2.setStroke(new BasicStroke(10, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
    g2.setBackground(Color.white);
    g2.setColor(Color.black);

    Path2D p = getPath(0, 0, 20);
    g2.draw(p);

    if (!(new Color(im.getRGB(20, 19))).equals(Color.black)) {
        throw new Exception("This pixel should be black");
    }
}
 
Example 17
/**
 * Renders contours to the passed image.
 *
 * @param destinationImage Image must be this.scale times larger than the
 * grid.
 * @param grid Grid with elevation values.
 * @param slopeGrid Grid with slope values.
 * @param progress Progress indicator. Not used when scale is 1.
 */
public void renderToImage(BufferedImage destinationImage, Grid grid, Grid slopeGrid, ProgressIndicator progress) {
    if (destinationImage == null) {
        throw new IllegalArgumentException();
    }
    this.image = destinationImage;
    this.progress = progress;
    this.imageBuffer = ((DataBufferInt) (image.getRaster().getDataBuffer())).getData();
    this.smoothGrid = new LowPassOperator(aspectGaussBlur).operate(grid);
    super.operate(grid, slopeGrid);
}
 
Example 18
public static void computeRegions(ImageReadParam param,
                                  int srcWidth,
                                  int srcHeight,
                                  BufferedImage image,
                                  Rectangle srcRegion,
                                  Rectangle destRegion) {
    ImageReader.computeRegions(param,
                               srcWidth,
                               srcHeight,
                               image,
                               srcRegion,
                               destRegion);
}
 
Example 19
public static void main(final String[] args) {
    for (final AffineTransform atfm : TRANSFORMS) {
        for (final int viType : TRANSPARENCIES) {
            for (final int biType : TYPES) {
                final BufferedImage bi = makeUnmanagedBI(biType);
                final VolatileImage vi = makeVI(viType);
                final long time = test(bi, vi, atfm) / 1000000000;
                if (time > 1) {
                    throw new RuntimeException(String.format(
                            "drawImage is slow: %d seconds", time));
                }
            }
        }
    }
}
 
Example 20
public void testReadingDoesNotCrash() throws IOException {
  InputStream resource = WmfReadingTest.class.getResourceAsStream( "anim0002.wmf" );
  assertNotNull( resource );
  WmfFile wmfFile = new WmfFile( resource, 800, 600 );
  BufferedImage bi = new BufferedImage( 800, 600, BufferedImage.TYPE_4BYTE_ABGR );
  Graphics2D graphics = bi.createGraphics();
  wmfFile.draw( graphics, new Rectangle2D.Double( 0, 0, 800, 600 ) );
  graphics.dispose();
}
 
Example 21
Source Project: openjdk-jdk9   Source File: DrawRect.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static void test(final BufferedImage gold, final BufferedImage bi)
        throws IOException {
    for (int x = 0; x < size; x++) {
        for (int y = 0; y < size; y++) {
            if (gold.getRGB(x, y) != bi.getRGB(x, y)) {
                ImageIO.write(gold, "png", new File("gold.png"));
                ImageIO.write(bi, "png", new File("image.png"));
                throw new RuntimeException("wrong color");
            }
        }
    }
}
 
Example 22
Source Project: FlatLaf   Source File: ScaledImageIcon.java    License: Apache License 2.0 5 votes vote down vote up
private BufferedImage image2bufferedImage( Image image ) {
	if( image instanceof BufferedImage )
		return (BufferedImage) image;

	BufferedImage bufferedImage = new BufferedImage( image.getWidth( null ),
		image.getHeight( null ), BufferedImage.TYPE_INT_ARGB );
	Graphics2D g = bufferedImage.createGraphics();
	try {
		g.drawImage( image, 0, 0, null );
	} finally {
		g.dispose();
	}
	return bufferedImage;
}
 
Example 23
Source Project: MyBox   Source File: FxmlImageManufacture.java    License: Apache License 2.0 5 votes vote down vote up
public static Image scaleImage(Image image, int width, int height) {
    if (width == image.getWidth() && height == image.getHeight()) {
        return image;
    }
    BufferedImage source = SwingFXUtils.fromFXImage(image, null);
    BufferedImage target = mara.mybox.image.ImageManufacture.scaleImage(source, width, height);
    Image newImage = SwingFXUtils.toFXImage(target, null);
    return newImage;
}
 
Example 24
Source Project: hifive-pitalium   Source File: AssertionView_VerifyTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 個別に撮影したScreenshotと保存済みScreenshotの比較 => 検証失敗
 */
@Test
public void verifyScreenshot_failed() throws Exception {
	BufferedImage image = ImageIO.read(getClass().getResource("images/hifive_logo_part.png"));

	when(testResultManager.getPersister().loadTargetResults(any(PersistMetadata.class)))
			.thenReturn(createScreenshotResult(image).getTargetResults());

	expectedException.expect(AssertionError.class);
	expectedException.expectMessage(startsWith("Verified 1 errors"));

	assertionView.verifyScreenshot(screenshotResult);
	assertTrue(true);
}
 
Example 25
Source Project: JavaWeb   Source File: ImageUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static byte[] scale(byte[] img, int height, int width,boolean flag,String imageType) throws Exception{
	double ratio = 0.0; //缩放比例
	InputStream inputStream = new ByteArrayInputStream(img);
	BufferedImage bi = ImageIO.read(inputStream);
	Image itemp = bi.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);
	//计算比例
	if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
		if (bi.getHeight() > bi.getWidth()) {
			ratio = (new Integer(height)).doubleValue() / bi.getHeight();
		} else {
			ratio = (new Integer(width)).doubleValue() / bi.getWidth();
		}
		AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
		itemp = op.filter(bi, null);
	}
	if (flag) {//补白
		BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
		Graphics2D g = image.createGraphics();
		g.setColor(Color.white);
		g.fillRect(0, 0, width, height);
		if (width == itemp.getWidth(null)){
			g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null),Color.white, null);
		}else{
			g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0,itemp.getWidth(null), itemp.getHeight(null),Color.white, null);
		}
		g.dispose();
		itemp = image;
	}
	ByteArrayOutputStream outputstream = new ByteArrayOutputStream();
	ImageIO.write((BufferedImage) itemp, imageType, outputstream);
	return outputstream.toByteArray();
}
 
Example 26
@Test
public void read() throws IOException {
	Resource logo = new ClassPathResource("logo.jpg", BufferedImageHttpMessageConverterTests.class);
	byte[] body = FileCopyUtils.copyToByteArray(logo.getInputStream());
	MockHttpInputMessage inputMessage = new MockHttpInputMessage(body);
	inputMessage.getHeaders().setContentType(new MediaType("image", "jpeg"));
	BufferedImage result = converter.read(BufferedImage.class, inputMessage);
	assertEquals("Invalid height", 500, result.getHeight());
	assertEquals("Invalid width", 750, result.getWidth());
}
 
Example 27
Source Project: openstock   Source File: LogAxisTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks that a TickUnit with a size of 0 doesn't crash.
 */
@Test
public void testRefreshTicksWithZeroTickUnit() {
    LogAxis axis = new LogAxis();
    AxisState state = new AxisState();
    BufferedImage image = new BufferedImage(200, 100,
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = image.createGraphics();
    Rectangle2D area = new Rectangle2D.Double(0.0, 0.0, 200, 100);
    axis.refreshTicks(g2, state, area, RectangleEdge.TOP);
}
 
Example 28
public static void main(final String[] args) throws IOException {
    for (final int viType : TRANSPARENCIES) {
        for (final int biType : TYPES) {
            BufferedImage bi = makeUnmanagedBI(biType);
            fill(bi);
            test(bi, viType);
        }
    }
}
 
Example 29
/**
 * 同じ画像と同じ領域を比較 => 成功
 */
@Test
public void testCompare() throws Exception {
	BufferedImage image = ImageIO.read(getClass().getResource("hifive_logo.png"));
	Rectangle rectangle = new Rectangle(0, 0, image.getWidth(), image.getHeight());
	ImageComparedResult result = new IgnoringClearPixelsImageComparator().compare(image, rectangle, image,
			rectangle);

	assertThat(result.isSucceeded(), is(true));
}
 
Example 30
Source Project: dl4j-tutorials   Source File: ImageUtils.java    License: MIT License 5 votes vote down vote up
public static INDArray toINDArrayBGR(BufferedImage image) {
    int height = image.getHeight();
    int width = image.getWidth();
    int bands = image.getRaster().getNumBands();

    int[] pixels = new int[width * height];
    pixels = getRGB(image, 0, 0, width, height, pixels);
    int[] shape = new int[] {bands, height, width};

    INDArray ret2 = Nd4j.create(1, width * height * bands);

    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            int idx = y * width + x;
            int color = pixels[idx];
            int[] argb = trimRGBColor(color);
            ret2.putScalar(idx, (argb[1]) & 0xFF);
            if (bands > 1) {
                ret2.putScalar(idx + pixels.length, (argb[2]) & 0xFF);
            }
            if (bands > 2) {
                ret2.putScalar(idx + pixels.length * 2, (argb[3]) & 0xFF);
            }
        }
    }
    return Nd4j.expandDims(ret2.reshape(shape), 0);
}