类java.awt.image.BufferedImage源码实例Demo

下面列出了怎么用java.awt.image.BufferedImage的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: hottub   文件: SunGraphics2D.java
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();
    }
}
 
源代码2 项目: Pixelitor   文件: PolarTiles.java
@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;
}
 
源代码3 项目: JImageHash   文件: CumulativeMatcherTest.java
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)));
	});
}
 
源代码4 项目: littleluck   文件: JMandelbrot.java
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());
    }
}
 
源代码5 项目: openjdk-jdk8u-backup   文件: ImageGenerator.java
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();
}
 
源代码6 项目: MeteoInfo   文件: CubeTexture.java
@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();
    }
}
 
源代码7 项目: Pixelitor   文件: JHUnderWater.java
@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;
}
 
源代码8 项目: jdk8u60   文件: GraphicsPrimitive.java
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;
}
 
源代码9 项目: hifive-pitalium   文件: PtlWebDriver.java
/**
 * 指定されたリスト内の最後の画像の高さ、スクロール量、ボーダー幅から<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));
	}
}
 
源代码10 项目: phoebus   文件: AWTFontCalibration.java
@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;
}
 
源代码11 项目: jdk8u_jdk   文件: PngPremultAlphaTest.java
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;
}
 
源代码12 项目: TencentKona-8   文件: SurfaceManager.java
/**
 * 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;
}
 
源代码13 项目: MyBox   文件: ImageGifFile.java
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());
    }
}
 
源代码14 项目: smart-admin   文件: KaptchaNoise.java
@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();
}
 
源代码15 项目: openjdk-jdk8u   文件: bug8016833.java
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);
}
 
源代码16 项目: openjdk-jdk8u   文件: Test7019861.java
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");
    }
}
 
/**
 * 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);
}
 
源代码18 项目: openjdk-jdk9   文件: AppletResourceTest.java
public static void computeRegions(ImageReadParam param,
                                  int srcWidth,
                                  int srcHeight,
                                  BufferedImage image,
                                  Rectangle srcRegion,
                                  Rectangle destRegion) {
    ImageReader.computeRegions(param,
                               srcWidth,
                               srcHeight,
                               image,
                               srcRegion,
                               destRegion);
}
 
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));
                }
            }
        }
    }
}
 
源代码20 项目: pentaho-reporting   文件: WmfReadingTest.java
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();
}
 
源代码21 项目: openjdk-jdk9   文件: DrawRect.java
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");
            }
        }
    }
}
 
源代码22 项目: FlatLaf   文件: ScaledImageIcon.java
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;
}
 
源代码23 项目: MyBox   文件: FxmlImageManufacture.java
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;
}
 
源代码24 项目: hifive-pitalium   文件: AssertionView_VerifyTest.java
/**
 * 個別に撮影した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);
}
 
源代码25 项目: JavaWeb   文件: ImageUtils.java
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();
}
 
@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());
}
 
源代码27 项目: openstock   文件: LogAxisTest.java
/**
 * 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);
}
 
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);
        }
    }
}
 
/**
 * 同じ画像と同じ領域を比較 => 成功
 */
@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));
}
 
源代码30 项目: dl4j-tutorials   文件: ImageUtils.java
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);
}
 
 类所在包
 同包方法