java.awt.image.BufferedImage

Here are the examples of the java api class java.awt.image.BufferedImage taken from open source projects.

1. HeadlessBufferedImage#main()

Project: openjdk
Source File: HeadlessBufferedImage.java
View license
public static void main(String args[]) {
    BufferedImage bi;
    bi = new BufferedImage(300, 300, BufferedImage.TYPE_3BYTE_BGR);
    bi = new BufferedImage(300, 300, BufferedImage.TYPE_4BYTE_ABGR);
    bi = new BufferedImage(300, 300, BufferedImage.TYPE_BYTE_BINARY);
    bi = new BufferedImage(300, 300, BufferedImage.TYPE_BYTE_GRAY);
    bi = new BufferedImage(300, 300, BufferedImage.TYPE_BYTE_INDEXED);
    bi = new BufferedImage(300, 300, BufferedImage.TYPE_INT_ARGB);
    bi = new BufferedImage(300, 300, BufferedImage.TYPE_INT_ARGB_PRE);
    bi = new BufferedImage(300, 300, BufferedImage.TYPE_INT_BGR);
    bi = new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);
    bi = new BufferedImage(300, 300, BufferedImage.TYPE_USHORT_565_RGB);
    bi = new BufferedImage(300, 300, BufferedImage.TYPE_USHORT_GRAY);
    bi = new BufferedImage(300, 300, BufferedImage.TYPE_USHORT_555_RGB);
    bi.getType();
    bi.getColorModel();
    bi.getRaster();
    bi.getAlphaRaster();
    bi.getRGB(1, 1);
    bi.getWidth();
    bi.getHeight();
    bi.getSource();
    bi.flush();
    bi.getGraphics();
    bi.createGraphics();
    BufferedImage bi2 = bi.getSubimage(10, 10, 200, 200);
    bi.isAlphaPremultiplied();
    bi.coerceData(true);
    bi.coerceData(false);
    bi.toString();
    bi.getSources();
    bi.getPropertyNames();
    bi.getMinX();
    bi.getMinY();
    bi.getSampleModel();
    bi.getNumXTiles();
    bi.getNumYTiles();
    bi.getMinTileX();
    bi.getMinTileY();
    bi.getTileWidth();
    bi.getTileHeight();
    bi.getTileGridXOffset();
    bi.getTileGridYOffset();
    bi.getData();
}

2. TestConvertBufferedImage#stripAlphaChannel()

View license
@Test
public void stripAlphaChannel() {
    BufferedImage a = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_4BYTE_ABGR);
    BufferedImage b = ConvertBufferedImage.stripAlphaChannel(a);
    assertTrue(a != b);
    assertEquals(3, b.getRaster().getNumBands());
    BufferedImage c = ConvertBufferedImage.stripAlphaChannel(b);
    assertTrue(b == c);
    a = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_BYTE_GRAY);
    c = ConvertBufferedImage.stripAlphaChannel(a);
    assertTrue(a == c);
    a = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_3BYTE_BGR);
    c = ConvertBufferedImage.stripAlphaChannel(a);
    assertTrue(a == c);
}

3. ColConvCCMTest#testSubImage()

Project: jdk7u-jdk
Source File: ColConvCCMTest.java
View license
static boolean testSubImage(int x0, int y0, int dx, int dy, int dataType, int rBits, int gBits, int bBits, int cs, BufferedImage gldImage, double accuracy) {
    BufferedImage src = ImageFactory.createCCMImage(cs, dataType);
    BufferedImage subSrc = src.getSubimage(x0, y0, dx, dy);
    BufferedImage dst = ImageFactory.createDstImage(BufferedImage.TYPE_INT_RGB);
    BufferedImage subDst = dst.getSubimage(x0, y0, dx, dy);
    ColorConvertOp op = new ColorConvertOp(null);
    op.filter(subSrc, subDst);
    ImageComparator cmp = new ImageComparator(accuracy, rBits, gBits, bBits);
    boolean result = cmp.compare(subDst, gldImage, x0, y0, dx, dy);
    if (!result) {
        System.err.println(cmp.getStat());
    }
    return result;
}

4. ColConvDCMTest#testSubImage()

Project: jdk7u-jdk
Source File: ColConvDCMTest.java
View license
static boolean testSubImage(int x0, int y0, int dx, int dy, int type, int rBits, int gBits, int bBits, int cs, BufferedImage gldImage, double accuracy) {
    BufferedImage src = ImageFactory.createDCMImage(type, cs);
    BufferedImage subSrc = src.getSubimage(x0, y0, dx, dy);
    BufferedImage dst = ImageFactory.createDstImage(BufferedImage.TYPE_INT_RGB);
    BufferedImage subDst = dst.getSubimage(x0, y0, dx, dy);
    ColorConvertOp op = new ColorConvertOp(null);
    op.filter(subSrc, subDst);
    ImageComparator cmp = new ImageComparator(accuracy, rBits, gBits, bBits);
    boolean result = cmp.compare(subDst, gldImage, x0, y0, dx, dy);
    if (!result) {
        System.err.println(cmp.getStat());
    }
    return result;
}

5. ColConvCCMTest#testSubImage()

Project: openjdk
Source File: ColConvCCMTest.java
View license
static boolean testSubImage(int x0, int y0, int dx, int dy, int dataType, int rBits, int gBits, int bBits, int cs, BufferedImage gldImage, double accuracy) {
    BufferedImage src = ImageFactory.createCCMImage(cs, dataType);
    BufferedImage subSrc = src.getSubimage(x0, y0, dx, dy);
    BufferedImage dst = ImageFactory.createDstImage(BufferedImage.TYPE_INT_RGB);
    BufferedImage subDst = dst.getSubimage(x0, y0, dx, dy);
    ColorConvertOp op = new ColorConvertOp(null);
    op.filter(subSrc, subDst);
    ImageComparator cmp = new ImageComparator(accuracy, rBits, gBits, bBits);
    boolean result = cmp.compare(subDst, gldImage, x0, y0, dx, dy);
    if (!result) {
        System.err.println(cmp.getStat());
    }
    return result;
}

6. ColConvDCMTest#testSubImage()

Project: openjdk
Source File: ColConvDCMTest.java
View license
static boolean testSubImage(int x0, int y0, int dx, int dy, int type, int rBits, int gBits, int bBits, int cs, BufferedImage gldImage, double accuracy) {
    BufferedImage src = ImageFactory.createDCMImage(type, cs);
    BufferedImage subSrc = src.getSubimage(x0, y0, dx, dy);
    BufferedImage dst = ImageFactory.createDstImage(BufferedImage.TYPE_INT_RGB);
    BufferedImage subDst = dst.getSubimage(x0, y0, dx, dy);
    ColorConvertOp op = new ColorConvertOp(null);
    op.filter(subSrc, subDst);
    ImageComparator cmp = new ImageComparator(accuracy, rBits, gBits, bBits);
    boolean result = cmp.compare(subDst, gldImage, x0, y0, dx, dy);
    if (!result) {
        System.err.println(cmp.getStat());
    }
    return result;
}

7. CanvasTest#subsequentImagesCroppedCorrectly()

Project: thumbnailator
Source File: CanvasTest.java
View license
@Test
public void subsequentImagesCroppedCorrectly() {
    /*
		 * Original code was changing the width/height settings when cropping
		 * was disabled, and if the image was larger than the width/height
		 * specified for the Canvas object.
		 */
    // given
    BufferedImage img1 = new BufferedImage(120, 120, BufferedImage.TYPE_INT_ARGB);
    BufferedImage img2 = new BufferedImage(50, 50, BufferedImage.TYPE_INT_ARGB);
    ImageFilter filter = new Canvas(100, 100, Positions.CENTER, false);
    // when
    BufferedImage result1 = filter.apply(img1);
    BufferedImage result2 = filter.apply(img2);
    // then
    assertEquals(120, result1.getWidth());
    assertEquals(120, result1.getHeight());
    assertEquals(100, result2.getWidth());
    assertEquals(100, result2.getHeight());
}

8. VisualizeAverageDownSample#main()

View license
public static void main(String[] args) {
    BufferedImage original = UtilImageIO.loadImage(UtilIO.pathExample("simple_objects.jpg"));
    Planar<GrayF32> input = new Planar<GrayF32>(GrayF32.class, original.getWidth(), original.getHeight(), 3);
    ConvertBufferedImage.convertFromMulti(original, input, true, GrayF32.class);
    Planar<GrayF32> output = new Planar<GrayF32>(GrayF32.class, original.getWidth() / 3, original.getHeight() / 3, 3);
    Planar<GrayF32> output2 = new Planar<GrayF32>(GrayF32.class, original.getWidth() / 3, original.getHeight() / 3, 3);
    AverageDownSampleOps.down(input, output);
    new FDistort(input, output2).scaleExt().apply();
    BufferedImage outputFull = ConvertBufferedImage.convertTo_F32(output, null, true);
    BufferedImage outputFull2 = ConvertBufferedImage.convertTo_F32(output2, null, true);
    ShowImages.showWindow(original, "Original");
    ShowImages.showWindow(outputFull, "3x small average");
    ShowImages.showWindow(outputFull2, "3x small bilinear");
}

9. Rainbow4JTest#shouldApply_maskFilter_andShouldGive_smallDifference()

Project: galen
Source File: Rainbow4JTest.java
View license
@Test
public void shouldApply_maskFilter_andShouldGive_smallDifference() throws IOException {
    BufferedImage imageActual = Rainbow4J.loadImage(getClass().getResourceAsStream("/mask/actual.png"));
    BufferedImage imageExpected = Rainbow4J.loadImage(getClass().getResourceAsStream("/mask/expected-with-rect.png"));
    BufferedImage imageMask = Rainbow4J.loadImage(getClass().getResourceAsStream("/mask/mask.png"));
    ComparisonOptions options = new ComparisonOptions();
    List<ImageFilter> filters = new LinkedList<>();
    filters.add(new MaskFilter(new ImageHandler(imageMask)));
    options.setOriginalFilters(filters);
    ImageCompareResult result = Rainbow4J.compare(imageActual, imageExpected, options);
    assertThat(result.getTotalPixels(), is(57L));
    assertThat(result.getPercentage(), is(lessThan(0.25)));
}

10. Rainbow4JTest#shouldApply_maskFilter_andShouldGive_biggerDifference()

Project: galen
Source File: Rainbow4JTest.java
View license
@Test
public void shouldApply_maskFilter_andShouldGive_biggerDifference() throws IOException {
    BufferedImage imageActual = Rainbow4J.loadImage(getClass().getResourceAsStream("/mask/actual.png"));
    BufferedImage imageExpected = Rainbow4J.loadImage(getClass().getResourceAsStream("/mask/expected-with-rect-and-cross.png"));
    BufferedImage imageMask = Rainbow4J.loadImage(getClass().getResourceAsStream("/mask/mask.png"));
    ComparisonOptions options = new ComparisonOptions();
    List<ImageFilter> filters = new LinkedList<>();
    filters.add(new MaskFilter(new ImageHandler(imageMask)));
    options.setOriginalFilters(filters);
    ImageCompareResult result = Rainbow4J.compare(imageActual, imageExpected, options);
    assertThat(result.getTotalPixels(), is(7907L));
    assertThat(result.getPercentage(), is(lessThan(30.0)));
    assertThat(result.getPercentage(), is(greaterThan(28.0)));
}

11. MlibOpsTest#doTest()

Project: jdk7u-jdk
Source File: MlibOpsTest.java
View license
public static void doTest(BufferedImageOp op) {
    BufferedImage src = createSrcImage();
    BufferedImage dst = createImage();
    BufferedImage ret = null;
    try {
        ret = ImagingLib.filter(op, src, dst);
    } catch (Exception e) {
        throw new RuntimeException("Test FAILED.", e);
    }
    if (ret == null) {
        throw new RuntimeException("Test FAILED: null output");
    }
    System.out.println("ret: " + ret);
    System.out.println("Test PASSED for " + op.getClass().getName());
}

12. GraphicsUtils#loadDoubleFilterImage()

Project: LGame
Source File: GraphicsUtils.java
View license
/**
	 * ??????????
	 * 
	 * @param img
	 * @param width
	 * @param height
	 * @return
	 */
public static final BufferedImage loadDoubleFilterImage(final Image img, final int width, final int height) {
    BufferedImage img1 = GraphicsUtils.drawClipImage(img, width, height, 0, 0);
    BufferedImage img2 = GraphicsUtils.drawClipImage(img, width, height, width, 0);
    WritableRaster writableRaster1 = img1.getRaster();
    DataBuffer dataBuffer1 = writableRaster1.getDataBuffer();
    int[] basePixels1 = AWTDataBufferHelper.getDataInt(dataBuffer1);
    WritableRaster writableRaster2 = img2.getRaster();
    DataBuffer dataBuffer2 = writableRaster2.getDataBuffer();
    int[] basePixels2 = AWTDataBufferHelper.getDataInt(dataBuffer2);
    int length = basePixels2.length;
    for (int i = 0; i < length; i++) {
        if (basePixels2[i] >= LColor.getRGB(200, 200, 200)) {
            basePixels2[i] = 0xffffff;
        } else {
            basePixels2[i] = basePixels1[i];
        }
    }
    img1.flush();
    img1 = null;
    return img2;
}

13. CannyEdgeDetectorTest#testComic()

Project: LIRE
Source File: CannyEdgeDetectorTest.java
View license
public void testComic() throws IOException {
    BufferedImage in = ImageIO.read(new File("flower.jpg"));
    CannyEdgeDetector ced = new CannyEdgeDetector(in, 30, 80);
    BufferedImage filter = ced.filter();
    BufferedImage flower = PixelClustering.clusterPixels(in);
    WritableRaster raster = flower.getRaster();
    Graphics graphics = flower.getGraphics();
    graphics.setColor(Color.black);
    int[] tmp = new int[3];
    for (int x = 0; x < raster.getWidth(); x++) {
        for (int y = 0; y < raster.getHeight(); y++) {
            filter.getRaster().getPixel(x, y, tmp);
            if (tmp[0] < 10) {
                graphics.fillOval(x, y, 3, 4);
            }
        }
    }
    ImageIO.write(filter, "png", new File("flower-canny.png"));
    ImageIO.write(flower, "png", new File("flower-comic.png"));
}

14. MlibOpsTest#doTest()

Project: openjdk
Source File: MlibOpsTest.java
View license
public static void doTest(BufferedImageOp op) {
    BufferedImage src = createSrcImage();
    BufferedImage dst = createImage();
    BufferedImage ret = null;
    try {
        ret = ImagingLib.filter(op, src, dst);
    } catch (Exception e) {
        throw new RuntimeException("Test FAILED.", e);
    }
    if (ret == null) {
        throw new RuntimeException("Test FAILED: null output");
    }
    System.out.println("ret: " + ret);
    System.out.println("Test PASSED for " + op.getClass().getName());
}

15. WatermarkTest#inputContentsAreNotAltered()

Project: thumbnailator
Source File: WatermarkTest.java
View license
/**
	 * Checks that the input image contents are not altered.
	 */
@Test
public void inputContentsAreNotAltered() {
    // given
    BufferedImage originalImage = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB);
    BufferedImage copyImage = BufferedImages.copy(originalImage);
    BufferedImage watermarkImg = new BufferedImage(50, 50, BufferedImage.TYPE_INT_ARGB);
    ImageFilter filter = new Watermark(Positions.BOTTOM_CENTER, watermarkImg, 0.5f);
    // when
    filter.apply(originalImage);
    // then
    assertTrue(BufferedImageComparer.isSame(originalImage, copyImage));
}

16. BufferedImageSourceTest#appliesSourceRegion()

View license
/*
	 *
	 *     +------+-----------+
	 *     |XXXXXX|           |
	 *     |XXXXXX|           |
	 *     +------+           |
	 *     |      region      |
	 *     |                  |
	 *     |                  |
	 *     |                  |
	 *     |                  |
	 *     +------------------+
	 *                        source
	 */
@Test
public void appliesSourceRegion() throws IOException {
    // given
    BufferedImage sourceImage = ImageIO.read(new File("src/test/resources/Thumbnailator/grid.png"));
    BufferedImageSource source = new BufferedImageSource(sourceImage);
    source.setThumbnailParameter(new ThumbnailParameterBuilder().region(new Region(Positions.TOP_LEFT, new AbsoluteSize(40, 40))).size(20, 20).build());
    // when
    BufferedImage img = source.read();
    // then
    BufferedImage expectedImg = sourceImage.getSubimage(0, 0, 40, 40);
    assertTrue(BufferedImageComparer.isSame(expectedImg, img));
}

17. BufferedImageSourceTest#appliesSourceRegionTooBig()

View license
/*
	 *
	 *     +------------------+ source
	 *     |  +------------------+
	 *     |  |XXXXXXXXXXXXXXX|  |
	 *     |  |XXXXXXXXXXXXXXX|  |
	 *     |  |XX  final  XXXX|  |
	 *     |  |XX  region XXXX|  |
	 *     |  |XXXXXXXXXXXXXXX|  |
	 *     |  |XXXXXXXXXXXXXXX|  |
	 *     |  |XXXXXXXXXXXXXXX|  |
	 *     +--|---------------+  |
	 *        +------------------+
	 *                             region
	 */
@Test
public void appliesSourceRegionTooBig() throws IOException {
    // given
    BufferedImage sourceImage = ImageIO.read(new File("src/test/resources/Thumbnailator/grid.png"));
    BufferedImageSource source = new BufferedImageSource(sourceImage);
    source.setThumbnailParameter(new ThumbnailParameterBuilder().region(new Region(new Coordinate(20, 20), new AbsoluteSize(100, 100))).size(80, 80).build());
    // when
    BufferedImage img = source.read();
    // then
    BufferedImage expectedImg = sourceImage.getSubimage(20, 20, 80, 80);
    assertTrue(BufferedImageComparer.isSame(expectedImg, img));
}

18. BufferedImageSourceTest#appliesSourceRegionBeyondOrigin()

View license
/*
	 *   +-----------------+
	 *   |                 |
	 *   | +---------------|--+
	 *   | |XXXXXXXXXXXXXXX|  |
	 *   | |XXXXXXXXXXXXXXX|  |
	 *   | |XXXX final XXXX|  |
	 *   | |XXXX regionXXXX|  |
	 *   | |XXXXXXXXXXXXXXX|  |
	 *   | |XXXXXXXXXXXXXXX|  |
	 *   +-----------------+  |
	 *     |                region
	 *     +------------------+
	 *                        source
	 */
@Test
public void appliesSourceRegionBeyondOrigin() throws IOException {
    // given
    BufferedImage sourceImage = ImageIO.read(new File("src/test/resources/Thumbnailator/grid.png"));
    BufferedImageSource source = new BufferedImageSource(sourceImage);
    source.setThumbnailParameter(new ThumbnailParameterBuilder().region(new Region(new Coordinate(-20, -20), new AbsoluteSize(100, 100))).size(80, 80).build());
    // when
    BufferedImage img = source.read();
    // then
    BufferedImage expectedImg = sourceImage.getSubimage(0, 0, 80, 80);
    assertTrue(BufferedImageComparer.isSame(expectedImg, img));
}

19. FileImageSourceTest#appliesSourceRegion()

View license
/*
	 *
	 *     +------+-----------+
	 *     |XXXXXX|           |
	 *     |XXXXXX|           |
	 *     +------+           |
	 *     |      region      |
	 *     |                  |
	 *     |                  |
	 *     |                  |
	 *     |                  |
	 *     +------------------+
	 *                        source
	 */
@Test
public void appliesSourceRegion() throws IOException {
    // given
    File sourceFile = new File("src/test/resources/Thumbnailator/grid.png");
    BufferedImage sourceImage = ImageIO.read(sourceFile);
    FileImageSource source = new FileImageSource(sourceFile);
    source.setThumbnailParameter(new ThumbnailParameterBuilder().region(new Region(Positions.TOP_LEFT, new AbsoluteSize(40, 40))).size(20, 20).build());
    // when
    BufferedImage img = source.read();
    // then
    BufferedImage expectedImg = sourceImage.getSubimage(0, 0, 40, 40);
    assertTrue(BufferedImageComparer.isRGBSimilar(expectedImg, img));
}

20. FileImageSourceTest#appliesSourceRegionTooBig()

View license
/*
	 *
	 *     +------------------+ source
	 *     |  +------------------+
	 *     |  |XXXXXXXXXXXXXXX|  |
	 *     |  |XXXXXXXXXXXXXXX|  |
	 *     |  |XX  final  XXXX|  |
	 *     |  |XX  region XXXX|  |
	 *     |  |XXXXXXXXXXXXXXX|  |
	 *     |  |XXXXXXXXXXXXXXX|  |
	 *     |  |XXXXXXXXXXXXXXX|  |
	 *     +--|---------------+  |
	 *        +------------------+
	 *                             region
	 */
@Test
public void appliesSourceRegionTooBig() throws IOException {
    // given
    File sourceFile = new File("src/test/resources/Thumbnailator/grid.png");
    BufferedImage sourceImage = ImageIO.read(sourceFile);
    FileImageSource source = new FileImageSource(sourceFile);
    source.setThumbnailParameter(new ThumbnailParameterBuilder().region(new Region(new Coordinate(20, 20), new AbsoluteSize(100, 100))).size(80, 80).build());
    // when
    BufferedImage img = source.read();
    // then
    BufferedImage expectedImg = sourceImage.getSubimage(20, 20, 80, 80);
    assertTrue(BufferedImageComparer.isRGBSimilar(expectedImg, img));
}

21. FileImageSourceTest#appliesSourceRegionBeyondOrigin()

View license
/*
	 *   +-----------------+
	 *   |                 |
	 *   | +---------------|--+
	 *   | |XXXXXXXXXXXXXXX|  |
	 *   | |XXXXXXXXXXXXXXX|  |
	 *   | |XXXX final XXXX|  |
	 *   | |XXXX regionXXXX|  |
	 *   | |XXXXXXXXXXXXXXX|  |
	 *   | |XXXXXXXXXXXXXXX|  |
	 *   +-----------------+  |
	 *     |                region
	 *     +------------------+
	 *                        source
	 */
@Test
public void appliesSourceRegionBeyondOrigin() throws IOException {
    // given
    File sourceFile = new File("src/test/resources/Thumbnailator/grid.png");
    BufferedImage sourceImage = ImageIO.read(sourceFile);
    FileImageSource source = new FileImageSource(sourceFile);
    source.setThumbnailParameter(new ThumbnailParameterBuilder().region(new Region(new Coordinate(-20, -20), new AbsoluteSize(100, 100))).size(80, 80).build());
    // when
    BufferedImage img = source.read();
    // then
    BufferedImage expectedImg = sourceImage.getSubimage(0, 0, 80, 80);
    assertTrue(BufferedImageComparer.isRGBSimilar(expectedImg, img));
}

22. InputStreamImageSourceTest#appliesSourceRegion()

View license
/*
	 *
	 *     +------+-----------+
	 *     |XXXXXX|           |
	 *     |XXXXXX|           |
	 *     +------+           |
	 *     |      region      |
	 *     |                  |
	 *     |                  |
	 *     |                  |
	 *     |                  |
	 *     +------------------+
	 *                        source
	 */
@Test
public void appliesSourceRegion() throws IOException {
    // given
    File sourceFile = new File("src/test/resources/Thumbnailator/grid.png");
    BufferedImage sourceImage = ImageIO.read(sourceFile);
    InputStreamImageSource source = new InputStreamImageSource(new FileInputStream(sourceFile));
    source.setThumbnailParameter(new ThumbnailParameterBuilder().region(new Region(Positions.TOP_LEFT, new AbsoluteSize(40, 40))).size(20, 20).build());
    // when
    BufferedImage img = source.read();
    // then
    BufferedImage expectedImg = sourceImage.getSubimage(0, 0, 40, 40);
    assertTrue(BufferedImageComparer.isRGBSimilar(expectedImg, img));
}

23. InputStreamImageSourceTest#appliesSourceRegionTooBig()

View license
/*
	 *
	 *     +------------------+ source
	 *     |  +------------------+
	 *     |  |XXXXXXXXXXXXXXX|  |
	 *     |  |XXXXXXXXXXXXXXX|  |
	 *     |  |XX  final  XXXX|  |
	 *     |  |XX  region XXXX|  |
	 *     |  |XXXXXXXXXXXXXXX|  |
	 *     |  |XXXXXXXXXXXXXXX|  |
	 *     |  |XXXXXXXXXXXXXXX|  |
	 *     +--|---------------+  |
	 *        +------------------+
	 *                             region
	 */
@Test
public void appliesSourceRegionTooBig() throws IOException {
    // given
    File sourceFile = new File("src/test/resources/Thumbnailator/grid.png");
    BufferedImage sourceImage = ImageIO.read(sourceFile);
    InputStreamImageSource source = new InputStreamImageSource(new FileInputStream(sourceFile));
    source.setThumbnailParameter(new ThumbnailParameterBuilder().region(new Region(new Coordinate(20, 20), new AbsoluteSize(100, 100))).size(80, 80).build());
    // when
    BufferedImage img = source.read();
    // then
    BufferedImage expectedImg = sourceImage.getSubimage(20, 20, 80, 80);
    assertTrue(BufferedImageComparer.isRGBSimilar(expectedImg, img));
}

24. InputStreamImageSourceTest#appliesSourceRegionBeyondOrigin()

View license
/*
	 *   +-----------------+
	 *   |                 |
	 *   | +---------------|--+
	 *   | |XXXXXXXXXXXXXXX|  |
	 *   | |XXXXXXXXXXXXXXX|  |
	 *   | |XXXX final XXXX|  |
	 *   | |XXXX regionXXXX|  |
	 *   | |XXXXXXXXXXXXXXX|  |
	 *   | |XXXXXXXXXXXXXXX|  |
	 *   +-----------------+  |
	 *     |                region
	 *     +------------------+
	 *                        source
	 */
@Test
public void appliesSourceRegionBeyondOrigin() throws IOException {
    // given
    File sourceFile = new File("src/test/resources/Thumbnailator/grid.png");
    BufferedImage sourceImage = ImageIO.read(sourceFile);
    InputStreamImageSource source = new InputStreamImageSource(new FileInputStream(sourceFile));
    source.setThumbnailParameter(new ThumbnailParameterBuilder().region(new Region(new Coordinate(-20, -20), new AbsoluteSize(100, 100))).size(80, 80).build());
    // when
    BufferedImage img = source.read();
    // then
    BufferedImage expectedImg = sourceImage.getSubimage(0, 0, 80, 80);
    assertTrue(BufferedImageComparer.isRGBSimilar(expectedImg, img));
}

25. URLImageSourceTest#appliesSourceRegion()

View license
/*
	 *
	 *     +------+-----------+
	 *     |XXXXXX|           |
	 *     |XXXXXX|           |
	 *     +------+           |
	 *     |      region      |
	 *     |                  |
	 *     |                  |
	 *     |                  |
	 *     |                  |
	 *     +------------------+
	 *                        source
	 */
@Test
public void appliesSourceRegion() throws IOException {
    // given
    File sourceFile = new File("src/test/resources/Thumbnailator/grid.png");
    BufferedImage sourceImage = ImageIO.read(sourceFile);
    URLImageSource source = new URLImageSource(new URL("file:src/test/resources/Thumbnailator/grid.png"));
    source.setThumbnailParameter(new ThumbnailParameterBuilder().region(new Region(Positions.TOP_LEFT, new AbsoluteSize(40, 40))).size(20, 20).build());
    // when
    BufferedImage img = source.read();
    // then
    BufferedImage expectedImg = sourceImage.getSubimage(0, 0, 40, 40);
    assertTrue(BufferedImageComparer.isRGBSimilar(expectedImg, img));
}

26. URLImageSourceTest#appliesSourceRegionTooBig()

View license
/*
	 *
	 *     +------------------+ source
	 *     |  +------------------+
	 *     |  |XXXXXXXXXXXXXXX|  |
	 *     |  |XXXXXXXXXXXXXXX|  |
	 *     |  |XX  final  XXXX|  |
	 *     |  |XX  region XXXX|  |
	 *     |  |XXXXXXXXXXXXXXX|  |
	 *     |  |XXXXXXXXXXXXXXX|  |
	 *     |  |XXXXXXXXXXXXXXX|  |
	 *     +--|---------------+  |
	 *        +------------------+
	 *                             region
	 */
@Test
public void appliesSourceRegionTooBig() throws IOException {
    // given
    File sourceFile = new File("src/test/resources/Thumbnailator/grid.png");
    BufferedImage sourceImage = ImageIO.read(sourceFile);
    URLImageSource source = new URLImageSource(new URL("file:src/test/resources/Thumbnailator/grid.png"));
    source.setThumbnailParameter(new ThumbnailParameterBuilder().region(new Region(new Coordinate(20, 20), new AbsoluteSize(100, 100))).size(80, 80).build());
    // when
    BufferedImage img = source.read();
    // then
    BufferedImage expectedImg = sourceImage.getSubimage(20, 20, 80, 80);
    assertTrue(BufferedImageComparer.isRGBSimilar(expectedImg, img));
}

27. URLImageSourceTest#appliesSourceRegionBeyondOrigin()

View license
/*
	 *   +-----------------+
	 *   |                 |
	 *   | +---------------|--+
	 *   | |XXXXXXXXXXXXXXX|  |
	 *   | |XXXXXXXXXXXXXXX|  |
	 *   | |XXXX final XXXX|  |
	 *   | |XXXX regionXXXX|  |
	 *   | |XXXXXXXXXXXXXXX|  |
	 *   | |XXXXXXXXXXXXXXX|  |
	 *   +-----------------+  |
	 *     |                region
	 *     +------------------+
	 *                        source
	 */
@Test
public void appliesSourceRegionBeyondOrigin() throws IOException {
    // given
    File sourceFile = new File("src/test/resources/Thumbnailator/grid.png");
    BufferedImage sourceImage = ImageIO.read(sourceFile);
    URLImageSource source = new URLImageSource(new URL("file:src/test/resources/Thumbnailator/grid.png"));
    source.setThumbnailParameter(new ThumbnailParameterBuilder().region(new Region(new Coordinate(-20, -20), new AbsoluteSize(100, 100))).size(80, 80).build());
    // when
    BufferedImage img = source.read();
    // then
    BufferedImage expectedImg = sourceImage.getSubimage(0, 0, 80, 80);
    assertTrue(BufferedImageComparer.isRGBSimilar(expectedImg, img));
}

28. ThumbnailsBuilderInputOutputTest#of_BufferedImages_iterableBufferedImages_NoOutputFormatSpecified()

View license
/**
	 * Test for the [email protected] Thumbnails.Builder} class where,
	 * <ol>
	 * <li>Thumbnails.of(BufferedImage, BufferedImage)</li>
	 * <li>iterableBufferedImages()</li>
	 * </ol>
	 * and the expected outcome is,
	 * <ol>
	 * <li>Processing completes successfully.</li>
	 * </ol>
	 * @throws IOException
	 */
@Test
public void of_BufferedImages_iterableBufferedImages_NoOutputFormatSpecified() throws IOException {
    // given
    BufferedImage img = new BufferedImageBuilder(200, 200).build();
    // when
    Iterable<BufferedImage> thumbnails = Thumbnails.of(img, img).size(50, 50).iterableBufferedImages();
    // then
    Iterator<BufferedImage> iter = thumbnails.iterator();
    BufferedImage thumbnail1 = iter.next();
    assertEquals(50, thumbnail1.getWidth());
    assertEquals(50, thumbnail1.getHeight());
    BufferedImage thumbnail2 = iter.next();
    assertEquals(50, thumbnail2.getWidth());
    assertEquals(50, thumbnail2.getHeight());
    assertFalse(iter.hasNext());
}

29. VisualConversionTest#test()

View license
@Test
public void test() throws IOException, TranscoderException, InstantiationException, IllegalAccessException {
    // verify bounds
    QualifiedResource svg = qualifiedSVGResourceFactory.fromSVGFile(new File(PATH_IN + filename + ".svg"));
    Rectangle rect = svg.getBounds();
    Assert.assertNotNull(rect);
    plugin.transcode(svg, svg.getDensity().getValue(), new File(PATH_OUT), null);
    BufferedImage transcoded = ImageIO.read(new FileInputStream(new File(PATH_OUT, svg.getName() + ".png")));
    BufferedImage original = ImageIO.read(new FileInputStream(new File(PATH_IN + svg.getName() + ".pngtest")));
    assertEquals(0, bufferedImagesEqual(transcoded, original), 0.1);
}

30. BuildAndDecodeTest#ninePatchImageColorTest()

Project: Apktool
Source File: BuildAndDecodeTest.java
View license
@Test
public void ninePatchImageColorTest() throws BrutException, IOException {
    char slash = File.separatorChar;
    String location = slash + "res" + slash + "drawable-xhdpi" + slash;
    File control = new File((sTestOrigDir + location), "9patch.9.png");
    File test = new File((sTestNewDir + location), "9patch.9.png");
    BufferedImage controlImage = ImageIO.read(control);
    BufferedImage testImage = ImageIO.read(test);
    // lets start with 0,0 - empty
    assertEquals(controlImage.getRGB(0, 0), testImage.getRGB(0, 0));
    // then with 30, 0 - black
    assertEquals(controlImage.getRGB(30, 0), testImage.getRGB(30, 0));
    // then 30, 30 - blue
    assertEquals(controlImage.getRGB(30, 30), testImage.getRGB(30, 30));
}

31. FormatRed#copyData()

Project: batik
Source File: FormatRed.java
View license
public WritableRaster copyData(WritableRaster wr) {
    ColorModel cm = getColorModel();
    CachableRed cr = getSource();
    ColorModel srcCM = cr.getColorModel();
    SampleModel srcSM = cr.getSampleModel();
    srcSM = srcSM.createCompatibleSampleModel(wr.getWidth(), wr.getHeight());
    WritableRaster srcWR;
    srcWR = Raster.createWritableRaster(srcSM, new Point(wr.getMinX(), wr.getMinY()));
    getSource().copyData(srcWR);
    BufferedImage srcBI = new BufferedImage(srcCM, srcWR.createWritableTranslatedChild(0, 0), srcCM.isAlphaPremultiplied(), null);
    BufferedImage dstBI = new BufferedImage(cm, wr.createWritableTranslatedChild(0, 0), cm.isAlphaPremultiplied(), null);
    GraphicsUtil.copyData(srcBI, dstBI);
    return wr;
}

32. MorphologyOp#createCompatibleDestImage()

Project: batik
Source File: MorphologyOp.java
View license
public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM) {
    BufferedImage dest = null;
    if (destCM == null)
        destCM = src.getColorModel();
    WritableRaster wr;
    wr = destCM.createCompatibleWritableRaster(src.getWidth(), src.getHeight());
    checkCompatible(destCM, wr.getSampleModel());
    dest = new BufferedImage(destCM, wr, destCM.isAlphaPremultiplied(), null);
    return dest;
}

33. Utilities#createGradientMask()

Project: beautyeye
Source File: Utilities.java
View license
public static BufferedImage createGradientMask(int width, int height, int orientation) {
    // algorithm derived from Romain Guy's blog
    BufferedImage gradient = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = gradient.createGraphics();
    GradientPaint paint = new GradientPaint(0.0f, 0.0f, new Color(1.0f, 1.0f, 1.0f, 1.0f), orientation == SwingConstants.HORIZONTAL ? width : 0.0f, orientation == SwingConstants.VERTICAL ? height : 0.0f, new Color(1.0f, 1.0f, 1.0f, 0.0f));
    g.setPaint(paint);
    g.fill(new Rectangle2D.Double(0, 0, width, height));
    g.dispose();
    gradient.flush();
    return gradient;
}

34. VisualizeHoughFoot#process()

Project: BoofCV
Source File: VisualizeHoughFoot.java
View license
public void process(BufferedImage image) {
    I input = GeneralizedImageOps.createSingleBand(imageType, image.getWidth(), image.getHeight());
    I blur = GeneralizedImageOps.createSingleBand(imageType, image.getWidth(), image.getHeight());
    ConvertBufferedImage.convertFromSingle(image, input, imageType);
    GBlurImageOps.gaussian(input, blur, -1, 2, null);
    DetectLineHoughFoot<I, D> alg = FactoryDetectLineAlgs.houghFoot(new ConfigHoughFoot(6, 12, 5, 25, 10), imageType, derivType);
    ImageLinePanel gui = new ImageLinePanel();
    gui.setBackground(image);
    gui.setLines(alg.detect(blur));
    gui.setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
    BufferedImage renderedTran = VisualizeImageData.grayMagnitude(alg.getTransform().getTransform(), null, -1);
    BufferedImage renderedBinary = VisualizeBinaryData.renderBinary(alg.getBinary(), false, null);
    ShowImages.showWindow(renderedBinary, "Detected Edges");
    ShowImages.showWindow(renderedTran, "Parameter Space");
    ShowImages.showWindow(gui, "Detected Lines");
}

35. VisualizeWatershedApp#main()

Project: BoofCV
Source File: VisualizeWatershedApp.java
View license
public static void main(String[] args) {
    BufferedImage image = UtilImageIO.loadImage(UtilIO.pathExample("segment/berkeley_horses.jpg"));
    GrayU8 gray = new GrayU8(image.getWidth(), image.getHeight());
    ConvertBufferedImage.convertFrom(image, gray);
    WatershedVincentSoille1991 alg = FactorySegmentationAlg.watershed(ConnectRule.FOUR);
    alg.process(gray);
    GrayS32 pixelToRegion = alg.getOutput();
    VisualizeRegions.watersheds(pixelToRegion, image, 0);
    alg.removeWatersheds();
    int numRegions = alg.getTotalRegions();
    BufferedImage outRegions = VisualizeRegions.regions(pixelToRegion, numRegions, null);
    ShowImages.showWindow(image, "Watershed");
    ShowImages.showWindow(outRegions, "Regions");
}

36. FourierVisualizeApp#refreshAll()

Project: BoofCV
Source File: FourierVisualizeApp.java
View license
@Override
public void refreshAll(Object[] cookies) {
    if (image == null)
        return;
    panel.reset();
    BufferedImage buffMag = VisualizeImageData.grayMagnitude(magnitude, null, -1);
    BufferedImage buffPhase = VisualizeImageData.colorizeSign(phase, null, Math.PI);
    panel.addImage(inputImage, "Original");
    panel.addImage(buffMag, "Magnitude");
    panel.addImage(buffPhase, "Phase");
}

37. WaveletVisualizeApp#setActiveAlgorithm()

Project: BoofCV
Source File: WaveletVisualizeApp.java
View license
@Override
public void setActiveAlgorithm(int indexFamily, String name, Object cookie) {
    if (image == null)
        return;
    WaveletDescription<C> desc = (WaveletDescription<C>) cookie;
    WaveletTransform<T, W, C> waveletTran = FactoryWaveletTransform.create((Class) image.getClass(), desc, numLevels, 0, 255);
    panel.reset();
    W imageWavelet = waveletTran.transform(image, null);
    waveletTran.invert(imageWavelet, imageInv);
    // adjust the values inside the wavelet transform to make it easier to see
    UtilWavelet.adjustForDisplay(imageWavelet, waveletTran.getLevels(), 255);
    BufferedImage buffWavelet = VisualizeImageData.grayMagnitude(imageWavelet, null, 255);
    BufferedImage buffInv = ConvertBufferedImage.convertTo(imageInv, null, true);
    panel.addImage(buffWavelet, "Transform");
    panel.addImage(buffInv, "Inverse");
}

38. ExampleRemoveLensDistortion#displayResults()

View license
/**
	 * Displays results in a window for easy comparison..
	 */
private static void displayResults(BufferedImage orig, Planar<GrayF32> distortedImg, ImageDistort allInside, ImageDistort fullView) {
    // render the results
    Planar<GrayF32> undistortedImg = new Planar<GrayF32>(GrayF32.class, distortedImg.getWidth(), distortedImg.getHeight(), distortedImg.getNumBands());
    allInside.apply(distortedImg, undistortedImg);
    BufferedImage out1 = ConvertBufferedImage.convertTo(undistortedImg, null, true);
    fullView.apply(distortedImg, undistortedImg);
    BufferedImage out2 = ConvertBufferedImage.convertTo(undistortedImg, null, true);
    // display in a single window where the user can easily switch between images
    ListDisplayPanel panel = new ListDisplayPanel();
    panel.addItem(new ImagePanel(orig), "Original");
    panel.addItem(new ImagePanel(out1), "Undistorted All Inside");
    panel.addItem(new ImagePanel(out2), "Undistorted Full View");
    ShowImages.showWindow(panel, "Removing Lens Distortion", true);
}

39. ExampleAssociatePoints#main()

Project: BoofCV
Source File: ExampleAssociatePoints.java
View license
public static void main(String args[]) {
    Class imageType = GrayF32.class;
    //		Class imageType = GrayU8.class;
    // select which algorithms to use
    DetectDescribePoint detDesc = FactoryDetectDescribe.surfStable(new ConfigFastHessian(1, 2, 300, 1, 9, 4, 4), null, null, imageType);
    //				sift(new ConfigCompleteSift(0,5,600));
    ScoreAssociation scorer = FactoryAssociation.defaultScore(detDesc.getDescriptionType());
    AssociateDescription associate = FactoryAssociation.greedy(scorer, Double.MAX_VALUE, true);
    // load and match images
    ExampleAssociatePoints app = new ExampleAssociatePoints(detDesc, associate, imageType);
    BufferedImage imageA = UtilImageIO.loadImage(UtilIO.pathExample("stitch/kayak_01.jpg"));
    BufferedImage imageB = UtilImageIO.loadImage(UtilIO.pathExample("stitch/kayak_03.jpg"));
    app.associate(imageA, imageB);
}

40. ExampleDetectDescribe#main()

Project: BoofCV
Source File: ExampleDetectDescribe.java
View license
public static void main(String args[]) {
    Class imageType = GrayF32.class;
    DetectDescribePoint detDesc = createFromPremade(imageType);
    //		DetectDescribePoint detDesc = createFromComponents(imageType);
    // Might as well have this example do something useful, like associate two images
    ScoreAssociation scorer = FactoryAssociation.defaultScore(detDesc.getDescriptionType());
    AssociateDescription associate = FactoryAssociation.greedy(scorer, Double.MAX_VALUE, true);
    // load and match images
    ExampleAssociatePoints app = new ExampleAssociatePoints(detDesc, associate, imageType);
    BufferedImage imageA = UtilImageIO.loadImage(UtilIO.pathExample("stitch/kayak_01.jpg"));
    BufferedImage imageB = UtilImageIO.loadImage(UtilIO.pathExample("stitch/kayak_03.jpg"));
    app.associate(imageA, imageB);
}

41. ExampleRemovePerspectiveDistortion#main()

View license
public static void main(String[] args) {
    // load a color image
    BufferedImage buffered = UtilImageIO.loadImage(UtilIO.pathExample("goals_and_stuff.jpg"));
    Planar<GrayF32> input = ConvertBufferedImage.convertFromMulti(buffered, null, true, GrayF32.class);
    RemovePerspectiveDistortion<Planar<GrayF32>> removePerspective = new RemovePerspectiveDistortion<Planar<GrayF32>>(400, 500, ImageType.pl(3, GrayF32.class));
    // Order matters! top-left, top-right, bottom-right, bottom-left
    if (!removePerspective.apply(input, new Point2D_F64(267, 182), new Point2D_F64(542, 68), new Point2D_F64(519, 736), new Point2D_F64(276, 570))) {
        throw new RuntimeException("Failed!?!?");
    }
    Planar<GrayF32> output = removePerspective.getOutput();
    BufferedImage flat = ConvertBufferedImage.convertTo_F32(output, null, true);
    ShowImages.showWindow(buffered, "Original Image", true);
    ShowImages.showWindow(flat, "Without Perspective Distortion", true);
}

42. ExamplePlanarImages#convertToGray()

Project: BoofCV
Source File: ExamplePlanarImages.java
View license
/**
	 * There is no real perfect way that everyone agrees on for converting color images into gray scale
	 * images.  Two examples of how to convert a Planar image into a gray scale image are shown
	 * in this example.
	 */
public static void convertToGray(BufferedImage input) {
    // convert the BufferedImage into a Planar
    Planar<GrayU8> image = ConvertBufferedImage.convertFromMulti(input, null, true, GrayU8.class);
    GrayU8 gray = new GrayU8(image.width, image.height);
    // creates a gray scale image by averaging intensity value across pixels
    GPixelMath.averageBand(image, gray);
    BufferedImage outputAve = ConvertBufferedImage.convertTo(gray, null);
    // create an output image just from the first band
    BufferedImage outputBand0 = ConvertBufferedImage.convertTo(image.getBand(0), null);
    gui.addImage(outputAve, "Gray Averaged");
    gui.addImage(outputBand0, "Band 0");
}

43. ExampleRectifyUncalibratedStereo#main()

View license
public static void main(String args[]) {
    // Load images with lens distortion removed.  If lens distortion has not been
    // removed then the results will be approximate
    String dir = UtilIO.pathExample("stereo/");
    BufferedImage imageA = UtilImageIO.loadImage(dir, "mono_wall_01_undist.jpg");
    BufferedImage imageB = UtilImageIO.loadImage(dir, "mono_wall_03_undist.jpg");
    // Find a set of point feature matches
    List<AssociatedPair> matches = ExampleFundamentalMatrix.computeMatches(imageA, imageB);
    // Prune matches using the epipolar constraint
    List<AssociatedPair> inliers = new ArrayList<AssociatedPair>();
    DenseMatrix64F F = ExampleFundamentalMatrix.robustFundamental(matches, inliers);
    // display the inlier matches found using the robust estimator
    AssociationPanel panel = new AssociationPanel(20);
    panel.setAssociation(inliers);
    panel.setImages(imageA, imageB);
    ShowImages.showWindow(panel, "Inlier Pairs");
    rectify(F, inliers, imageA, imageB);
}

44. JCodecMediaManager#openImage()

Project: BoofCV
Source File: JCodecMediaManager.java
View license
@Override
public BufferedImage openImage(String fileName) {
    BufferedImage b = cachedImage.get(fileName);
    if (b == null) {
        b = UtilImageIO.loadImage(fileName);
        if (b == null)
            throw new RuntimeException("Image cannot be found! " + fileName);
        cachedImage.put(fileName, b);
    }
    // return a copy of the image so that if it is modified strangeness won't happen
    BufferedImage c = new BufferedImage(b.getWidth(), b.getHeight(), b.getType());
    Graphics2D g2 = c.createGraphics();
    g2.drawImage(b, 0, 0, null);
    return c;
}

45. OverlayRgbDepthStreamsApp#process()

View license
public void process() {
    int w = UtilOpenKinect.getWidth(resolution);
    int h = UtilOpenKinect.getHeight(resolution);
    buffRgb = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    buffDepth = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    gui = ShowImages.showWindow(buffRgb, "Kinect Overlay");
    StreamOpenKinectRgbDepth stream = new StreamOpenKinectRgbDepth();
    Context kinect = Freenect.createContext();
    if (kinect.numDevices() < 0)
        throw new RuntimeException("No kinect found!");
    Device device = kinect.openDevice(0);
    stream.start(device, resolution, this);
}

46. PlaybackKinectLogApp#process()

Project: BoofCV
Source File: PlaybackKinectLogApp.java
View license
public void process() throws IOException {
    parseFrame(0);
    outRgb = new BufferedImage(rgb.getWidth(), rgb.getHeight(), BufferedImage.TYPE_INT_RGB);
    outDepth = new BufferedImage(depth.getWidth(), depth.getHeight(), BufferedImage.TYPE_INT_RGB);
    gui = new ImageGridPanel(1, 2, outRgb, outDepth);
    ShowImages.showWindow(gui, "Kinect Data");
    int frame = 1;
    while (true) {
        parseFrame(frame++);
        ConvertBufferedImage.convertTo_U8(rgb, outRgb, true);
        VisualizeImageData.disparity(depth, outDepth, 0, UtilOpenKinect.FREENECT_DEPTH_MM_MAX_VALUE, 0);
        gui.repaint();
        BoofMiscOps.pause(30);
    }
}

47. DefaultMediaManager#openImage()

Project: BoofCV
Source File: DefaultMediaManager.java
View license
@Override
public BufferedImage openImage(String fileName) {
    BufferedImage b = cachedImage.get(fileName);
    if (b == null) {
        b = UtilImageIO.loadImage(fileName);
        if (b == null)
            return null;
        cachedImage.put(fileName, b);
    }
    // return a copy of the image so that if it is modified strangeness won't happen
    BufferedImage c = new BufferedImage(b.getWidth(), b.getHeight(), b.getType());
    Graphics2D g2 = c.createGraphics();
    g2.drawImage(b, 0, 0, null);
    return c;
}

48. TestConvertBufferedImage#isSubImage()

View license
@Test
public void isSubImage() {
    BufferedImage a = new BufferedImage(20, 30, BufferedImage.TYPE_BYTE_GRAY);
    assertFalse(ConvertBufferedImage.isSubImage(a));
    BufferedImage b = a.getSubimage(0, 0, 20, 29);
    assertTrue(ConvertBufferedImage.isSubImage(b));
    b = a.getSubimage(0, 0, 19, 30);
    assertTrue(ConvertBufferedImage.isSubImage(b));
    b = a.getSubimage(0, 1, 20, 29);
    assertTrue(ConvertBufferedImage.isSubImage(b));
    b = a.getSubimage(1, 0, 19, 30);
    assertTrue(ConvertBufferedImage.isSubImage(b));
}

49. BaseFilter#createCompatibleDestImage()

Project: BroadleafCommerce
Source File: BaseFilter.java
View license
/* (non-Javadoc)
     * @see java.awt.image.BufferedImageOp#createCompatibleDestImage(java.awt.image.BufferedImage, java.awt.image.ColorModel)
     */
public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM) {
    BufferedImage image;
    if (destCM == null) {
        destCM = src.getColorModel();
        // Not much support for ICM
        if (destCM instanceof IndexColorModel) {
            destCM = ColorModel.getRGBdefault();
        }
    }
    int w = src.getWidth();
    int h = src.getHeight();
    image = new BufferedImage(destCM, destCM.createCompatibleWritableRaster(w, h), destCM.isAlphaPremultiplied(), null);
    return image;
}

50. BaseFilter#createCompatibleDestImage()

Project: BroadleafCommerce
Source File: BaseFilter.java
View license
public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM, int width, int height) {
    BufferedImage image;
    if (destCM == null) {
        destCM = src.getColorModel();
        // Not much support for ICM
        if (destCM instanceof IndexColorModel) {
            destCM = ColorModel.getRGBdefault();
        }
    }
    image = new BufferedImage(destCM, destCM.createCompatibleWritableRaster(width, height), destCM.isAlphaPremultiplied(), null);
    return image;
}

51. BaseFilter#createCompatibleDestImage()

Project: broadleaf_modify
Source File: BaseFilter.java
View license
/* (non-Javadoc)
     * @see java.awt.image.BufferedImageOp#createCompatibleDestImage(java.awt.image.BufferedImage, java.awt.image.ColorModel)
     */
public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM) {
    BufferedImage image;
    if (destCM == null) {
        destCM = src.getColorModel();
        // Not much support for ICM
        if (destCM instanceof IndexColorModel) {
            destCM = ColorModel.getRGBdefault();
        }
    }
    int w = src.getWidth();
    int h = src.getHeight();
    image = new BufferedImage(destCM, destCM.createCompatibleWritableRaster(w, h), destCM.isAlphaPremultiplied(), null);
    return image;
}

52. BaseFilter#createCompatibleDestImage()

Project: broadleaf_modify
Source File: BaseFilter.java
View license
public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM, int width, int height) {
    BufferedImage image;
    if (destCM == null) {
        destCM = src.getColorModel();
        // Not much support for ICM
        if (destCM instanceof IndexColorModel) {
            destCM = ColorModel.getRGBdefault();
        }
    }
    image = new BufferedImage(destCM, destCM.createCompatibleWritableRaster(width, height), destCM.isAlphaPremultiplied(), null);
    return image;
}

53. MapPalette#imageToBytes()

Project: Bukkit
Source File: MapPalette.java
View license
/**
     * Convert an Image to a byte[] using the palette.
     *
     * @param image The image to convert.
     * @return A byte[] containing the pixels of the image.
     * @deprecated Magic value
     */
@Deprecated
public static byte[] imageToBytes(Image image) {
    BufferedImage temp = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = temp.createGraphics();
    graphics.drawImage(image, 0, 0, null);
    graphics.dispose();
    int[] pixels = new int[temp.getWidth() * temp.getHeight()];
    temp.getRGB(0, 0, temp.getWidth(), temp.getHeight(), pixels, 0, temp.getWidth());
    byte[] result = new byte[temp.getWidth() * temp.getHeight()];
    for (int i = 0; i < pixels.length; i++) {
        result[i] = matchColor(new Color(pixels[i], true));
    }
    return result;
}

54. EditableResources#writeImageAsPNG()

Project: CodenameOne
Source File: EditableResources.java
View license
private void writeImageAsPNG(Image image, int type, DataOutputStream output) throws IOException {
    BufferedImage buffer = new BufferedImage(image.getWidth(), image.getHeight(), type);
    buffer.setRGB(0, 0, image.getWidth(), image.getHeight(), image.getRGB(), 0, image.getWidth());
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    ImageIO.write(buffer, "png", byteOut);
    byte[] data = byteOut.toByteArray();
    output.writeInt(data.length);
    output.write(data);
    output.writeInt(buffer.getWidth());
    output.writeInt(buffer.getHeight());
    output.writeBoolean(EncodedImage.create(data).isOpaque());
}

55. ByteSourceImageTest#checkGetBufferedImage()

View license
public void checkGetBufferedImage(final File file, final byte[] bytes) throws Exception {
    BufferedImage bufferedImage = Imaging.getBufferedImage(file);
    assertNotNull(bufferedImage);
    assertTrue(bufferedImage.getWidth() > 0);
    assertTrue(bufferedImage.getHeight() > 0);
    final int imageFileWidth = bufferedImage.getWidth();
    final int imageFileHeight = bufferedImage.getHeight();
    final BufferedImage imageBytes = Imaging.getBufferedImage(bytes);
    assertNotNull(imageBytes);
    assertTrue(imageFileWidth == imageBytes.getWidth());
    assertTrue(imageFileHeight == imageBytes.getHeight());
}

56. TiffSubImageTest#testSubImage()

View license
@Test
public void testSubImage() throws ImageReadException, ImageWriteException, IOException {
    BufferedImage src = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB);
    byte[] imageBytes = Imaging.writeImageToBytes(src, ImageFormats.TIFF, null);
    Map<String, Object> params = new TreeMap<>();
    params.put(TiffConstants.PARAM_KEY_SUBIMAGE_X, 0);
    params.put(TiffConstants.PARAM_KEY_SUBIMAGE_Y, 0);
    params.put(TiffConstants.PARAM_KEY_SUBIMAGE_WIDTH, 2);
    params.put(TiffConstants.PARAM_KEY_SUBIMAGE_HEIGHT, 3);
    BufferedImage image = Imaging.getBufferedImage(imageBytes, params);
    assertEquals(image.getWidth(), 2);
    assertEquals(image.getHeight(), 3);
}

57. NullParametersRoundtripTest#testNullParametersRoundtrip()

View license
@Theory
public void testNullParametersRoundtrip(final FormatInfo formatInfo) throws Exception {
    final BufferedImage testImage = TestImages.createFullColorImage(1, 1);
    final File temp1 = createTempFile("nullParameters.", "." + formatInfo.format.getExtension());
    Imaging.writeImage(testImage, temp1, formatInfo.format, null);
    Imaging.getImageInfo(temp1, null);
    Imaging.getImageSize(temp1, null);
    Imaging.getMetadata(temp1, null);
    Imaging.getICCProfile(temp1, null);
    BufferedImage imageRead = Imaging.getBufferedImage(temp1, null);
    assertNotNull(imageRead);
}

58. IconUtil#flip()

Project: consulo
Source File: IconUtil.java
View license
@NotNull
public static Icon flip(@NotNull Icon icon, boolean horizontal) {
    int w = icon.getIconWidth();
    int h = icon.getIconHeight();
    BufferedImage first = UIUtil.createImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = first.createGraphics();
    icon.paintIcon(new JPanel(), g, 0, 0);
    g.dispose();
    BufferedImage second = UIUtil.createImage(w, h, BufferedImage.TYPE_INT_ARGB);
    g = second.createGraphics();
    if (horizontal) {
        g.drawImage(first, 0, 0, w, h, w, 0, 0, h, null);
    } else {
        g.drawImage(first, 0, 0, w, h, 0, h, w, 0, null);
    }
    g.dispose();
    return new ImageIcon(second);
}

59. IconUtil#colorize()

Project: consulo
Source File: IconUtil.java
View license
@NotNull
public static Icon colorize(@NotNull final Icon source, @NotNull Color color, boolean keepGray) {
    float[] base = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null);
    final BufferedImage image = UIUtil.createImage(source.getIconWidth(), source.getIconHeight(), Transparency.TRANSLUCENT);
    final Graphics2D g = image.createGraphics();
    source.paintIcon(null, g, 0, 0);
    g.dispose();
    final BufferedImage img = UIUtil.createImage(source.getIconWidth(), source.getIconHeight(), Transparency.TRANSLUCENT);
    int[] rgba = new int[4];
    float[] hsb = new float[3];
    for (int y = 0; y < image.getRaster().getHeight(); y++) {
        for (int x = 0; x < image.getRaster().getWidth(); x++) {
            image.getRaster().getPixel(x, y, rgba);
            if (rgba[3] != 0) {
                Color.RGBtoHSB(rgba[0], rgba[1], rgba[2], hsb);
                int rgb = Color.HSBtoRGB(base[0], base[1] * (keepGray ? hsb[1] : 1f), base[2] * hsb[2]);
                img.getRaster().setPixel(x, y, new int[] { rgb >> 16 & 0xff, rgb >> 8 & 0xff, rgb & 0xff, rgba[3] });
            }
        }
    }
    return createImageIcon(img);
}

60. ShadowBorderPainter#createShadow()

Project: consulo
Source File: ShadowBorderPainter.java
View license
public static Shadow createShadow(Image source, int x, int y, boolean paintSource, int shadowSize) {
    int size = shadowSize;
    final float w = source.getWidth(null);
    final float h = source.getHeight(null);
    float ratio = w / h;
    float deltaX = size;
    float deltaY = size / ratio;
    final Image scaled = source.getScaledInstance((int) (w + deltaX), (int) (h + deltaY), Image.SCALE_SMOOTH);
    final BufferedImage s = GraphicsUtilities.createCompatibleTranslucentImage(scaled.getWidth(null), scaled.getHeight(null));
    final Graphics2D graphics = (Graphics2D) s.getGraphics();
    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    graphics.drawImage(scaled, 0, 0, null);
    final BufferedImage shadow = new ShadowRenderer(size, .25f, Color.black).createShadow(s);
    if (paintSource) {
        final Graphics imgG = shadow.getGraphics();
        final double d = size * 0.5;
        imgG.drawImage(source, (int) (size + d), (int) (size + d / ratio), null);
    }
    return new Shadow(shadow, x - size - 5, y - size + 2);
}

61. ShadowMaker#processImage()

Project: diablo-js
Source File: ShadowMaker.java
View license
public static void processImage(String in, String out) throws IOException {
    File imageFile = new File(in);
    BufferedImage bufferedImage = ImageIO.read(imageFile);
    int width = bufferedImage.getWidth(null);
    int height = bufferedImage.getHeight(null);
    BufferedImage alphaImage = new BufferedImage((width + (height / 2)), height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = alphaImage.createGraphics();
    g2d.drawImage(bufferedImage, (height / 2), 0, null);
    g2d.dispose();
    makeShadow(alphaImage);
    ImageIO.write(alphaImage, "png", new File(out));
}

62. AbstractGraphics2DAdapter#createGrayBufferedImageWithAlpha()

Project: fop
Source File: AbstractGraphics2DAdapter.java
View license
private static BufferedImage createGrayBufferedImageWithAlpha(int width, int height) {
    BufferedImage bi;
    boolean alphaPremultiplied = true;
    int bands = 2;
    int[] bits = new int[bands];
    for (int i = 0; i < bands; i++) {
        bits[i] = 8;
    }
    ColorModel cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY), bits, true, alphaPremultiplied, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE);
    WritableRaster wr = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, width, height, bands, new Point(0, 0));
    bi = new BufferedImage(cm, wr, alphaPremultiplied, null);
    return bi;
}

63. AbstractImageHandlerGraphics2D#createGrayBufferedImageWithAlpha()

View license
private static BufferedImage createGrayBufferedImageWithAlpha(int width, int height) {
    BufferedImage bi;
    boolean alphaPremultiplied = true;
    int bands = 2;
    int[] bits = new int[bands];
    for (int i = 0; i < bands; i++) {
        bits[i] = 8;
    }
    ColorModel cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY), bits, true, alphaPremultiplied, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE);
    WritableRaster wr = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, width, height, bands, new Point(0, 0));
    bi = new BufferedImage(cm, wr, alphaPremultiplied, null);
    return bi;
}

64. Rainbow4JTest#shouldSave_imageAsPng()

Project: galen
Source File: Rainbow4JTest.java
View license
@Test
public void shouldSave_imageAsPng() throws IOException {
    BufferedImage image = Rainbow4J.loadImage(getClass().getResource("/test-spectrum-black-white-1.png").getFile());
    File file = File.createTempFile("test-rainbow4j-image", ".png");
    Rainbow4J.saveImage(image, file);
    assertThat("File should exist", file.exists());
    BufferedImage image2 = Rainbow4J.loadImage(file.getAbsolutePath());
    assertThat("Width should be same as original width", image2.getWidth(), is(image.getWidth()));
    assertThat("Height should be same as original height", image2.getHeight(), is(image.getHeight()));
}

65. Rainbow4JTest#shouldCompare_images()

Project: galen
Source File: Rainbow4JTest.java
View license
@Test(dataProvider = "imageCompareProvider")
public void shouldCompare_images(int pixelSmooth, double approxPercentage, long expectedTotalPixels) throws IOException {
    BufferedImage imageA = Rainbow4J.loadImage(getClass().getResource("/comp-image-1.jpg").getFile());
    BufferedImage imageB = Rainbow4J.loadImage(getClass().getResource("/comp-image-2.jpg").getFile());
    ComparisonOptions options = new ComparisonOptions();
    if (pixelSmooth > 0) {
        options.addFilterBoth(new BlurFilter(pixelSmooth));
    }
    ImageCompareResult diff = Rainbow4J.compare(imageA, imageB, options);
    assertThat(diff.getPercentage(), is(greaterThan(approxPercentage - 0.02)));
    assertThat(diff.getPercentage(), is(lessThan(approxPercentage + 0.02)));
    assertThat(diff.getTotalPixels(), is(expectedTotalPixels));
}

66. Rainbow4JTest#shouldCompare_sameImages_ofDifferentSizes()

Project: galen
Source File: Rainbow4JTest.java
View license
@Test
public void shouldCompare_sameImages_ofDifferentSizes() throws IOException {
    BufferedImage imageA = Rainbow4J.loadImage(getClass().getResource("/comp-image-1.jpg").getFile());
    BufferedImage imageB = Rainbow4J.loadImage(getClass().getResource("/comp-image-1-scaled-down.jpg").getFile());
    ComparisonOptions options = new ComparisonOptions();
    options.setStretchToFit(true);
    options.setTolerance(10);
    ImageCompareResult diff = Rainbow4J.compare(imageA, imageB, options);
    assertThat(diff.getTotalPixels(), is(6670L));
    assertThat(diff.getPercentage(), is(lessThan(2.86)));
    assertThat(diff.getPercentage(), is(greaterThan(2.56)));
}

67. Rainbow4JTest#shouldCompare_differentImages_withDifferentSizes()

Project: galen
Source File: Rainbow4JTest.java
View license
@Test
public void shouldCompare_differentImages_withDifferentSizes() throws IOException {
    BufferedImage imageA = Rainbow4J.loadImage(getClass().getResource("/comp-image-1.jpg").getFile());
    BufferedImage imageB = Rainbow4J.loadImage(getClass().getResource("/comp-image-3-scaled-down.jpg").getFile());
    ComparisonOptions options = new ComparisonOptions();
    options.setStretchToFit(true);
    options.setTolerance(10);
    ImageCompareResult diff = Rainbow4J.compare(imageA, imageB, options);
    assertThat(diff.getTotalPixels(), is(greaterThan(14800L)));
    assertThat(diff.getTotalPixels(), is(lessThan(15500L)));
    assertThat(diff.getPercentage(), is(greaterThan(5.9)));
    assertThat(diff.getPercentage(), is(lessThan(6.1)));
}

68. Rainbow4JTest#shouldCompare_images_withOnlyPartialRegions()

Project: galen
Source File: Rainbow4JTest.java
View license
@Test
public void shouldCompare_images_withOnlyPartialRegions() throws IOException {
    BufferedImage imageA = Rainbow4J.loadImage(getClass().getResource("/page-screenshot.png").getFile());
    BufferedImage imageB = Rainbow4J.loadImage(getClass().getResource("/page-sample-correct.png").getFile());
    ComparisonOptions options = new ComparisonOptions();
    options.setTolerance(2);
    ImageCompareResult diff = Rainbow4J.compare(imageA, imageB, new Rectangle(100, 90, 100, 40), new Rectangle(40, 40, 100, 40), options);
    assertThat(diff.getTotalPixels(), is(lessThan(2L)));
    assertThat(diff.getPercentage(), is(lessThan(0.01)));
}

69. Rainbow4JTest#shouldCompare_images_andReturn_comparisonMap()

Project: galen
Source File: Rainbow4JTest.java
View license
@Test
public void shouldCompare_images_andReturn_comparisonMap() throws IOException {
    BufferedImage imageA = Rainbow4J.loadImage(getClass().getResource("/page-screenshot-1.png").getFile());
    BufferedImage imageB = Rainbow4J.loadImage(getClass().getResource("/page-screenshot-1-sample-1.png").getFile());
    ComparisonOptions options = new ComparisonOptions();
    options.addFilterBoth(new BlurFilter(1));
    options.setTolerance(100);
    ImageCompareResult diff = Rainbow4J.compare(imageA, imageB, new Rectangle(0, 70, 100, 64), new Rectangle(0, 0, imageB.getWidth(), imageB.getHeight()), options);
    assertThat(diff.getComparisonMap(), is(notNullValue()));
}

70. ImageUtils#scaleImageToWidth()

Project: greenhouse
Source File: ImageUtils.java
View license
/**
	 * Scale the image stored in the byte array to a specific width.
	 */
public static byte[] scaleImageToWidth(byte[] originalBytes, int scaledWidth) throws IOException {
    BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(originalBytes));
    int originalWidth = originalImage.getWidth();
    if (originalWidth <= scaledWidth) {
        return originalBytes;
    }
    int scaledHeight = (int) (originalImage.getHeight() * ((float) scaledWidth / (float) originalWidth));
    BufferedImage scaledImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = scaledImage.createGraphics();
    g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
    g.dispose();
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    ImageIO.write(scaledImage, "jpeg", byteStream);
    return byteStream.toByteArray();
}

71. RankLevelOcrTest#testRankLevel()

View license
private void testRankLevel(String filename, String expectedResult) throws Exception {
    URL res = OpponentNameOcrTest.class.getResource("/images/ranklevel/" + filename);
    BufferedImage bufferedImage = ImageIO.read(res);
    String rawResult = rankLevelOcr.performOcr(bufferedImage, 0);
    bufferedImage.flush();
    String parsedResult = rankLevelOcr.parseString(rawResult, 0);
    debugLog.debug("OCR for {} found raw \"{}\" parsed \"{}\"", filename, rawResult, parsedResult);
    org.junit.Assert.assertEquals("OCR of rank in " + filename + " did not match expected rank", expectedResult, parsedResult);
}

72. ScrollBarUI#paintTrack()

Project: HMCL
Source File: ScrollBarUI.java
View license
/** [email protected]} */
@Override
protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) {
    BufferedImage decImg = decBtnMousePressed ? SCROLL_DEC_PRESSED : decBtnMouseOver ? SCROLL_DEC_OVER : SCROLL_DEC_NORMAL;
    BufferedImage incImg = incBtnMousePressed ? SCROLL_INC_PRESSED : incBtnMouseOver ? SCROLL_INC_OVER : SCROLL_INC_NORMAL;
    Graphics2D g2 = (Graphics2D) g;
    AffineTransform origTransform = g2.getTransform();
    int scrollWidth = scrollbar.getWidth();
    if (scrollbar.getOrientation() == JScrollBar.VERTICAL) {
        scrollWidth = scrollbar.getHeight();
        g2.scale(1, -1);
        g2.rotate(-Math.PI / 2, 0, 0);
    }
    // draw track & bottons
    if (scrollbar.isEnabled()) {
        g.drawImage(decImg, 0, 0, scrollbar);
        //g.drawImage(BACKGROUND_ENABLED, 15, 0, scrollWidth - 15, 15, 0, 0, 1, 15, scrollbar);
        g.drawImage(incImg, scrollWidth - 15, 0, scrollbar);
    } else {
    //g.drawImage(BACKGROUND_DISABLED, 0, 0, scrollWidth, 15, 0, 0, 1, 15, scrollbar);
    }
    // undo any transform
    g2.setTransform(origTransform);
}

73. ImageData#resizeImage()

Project: incubator-fineract
Source File: ImageData.java
View license
public void resizeImage(InputStream in, OutputStream out, int maxWidth, int maxHeight) throws IOException {
    BufferedImage src = ImageIO.read(in);
    if (src.getWidth() <= maxWidth && src.getHeight() <= maxHeight) {
        out.write(getContent());
        return;
    }
    float widthRatio = (float) src.getWidth() / maxWidth;
    float heightRatio = (float) src.getHeight() / maxHeight;
    float scaleRatio = widthRatio > heightRatio ? widthRatio : heightRatio;
    // TODO(lindahl): Improve compressed image quality (perhaps quality
    // ratio)
    int newWidth = (int) (src.getWidth() / scaleRatio);
    int newHeight = (int) (src.getHeight() / scaleRatio);
    int colorModel = fileExtension == ContentRepositoryUtils.IMAGE_FILE_EXTENSION.JPEG ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
    BufferedImage target = new BufferedImage(newWidth, newHeight, colorModel);
    Graphics2D g = target.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.drawImage(src, 0, 0, newWidth, newHeight, Color.BLACK, null);
    g.dispose();
    ImageIO.write(target, fileExtension != null ? fileExtension.getValueWithoutDot() : "jpeg", out);
}

74. IconUtil#filterIcon()

Project: intellij-community
Source File: IconUtil.java
View license
@NotNull
private static Icon filterIcon(@NotNull Icon source, @NotNull Filter filter) {
    BufferedImage src = UIUtil.createImage(source.getIconWidth(), source.getIconHeight(), Transparency.TRANSLUCENT);
    Graphics2D g = src.createGraphics();
    source.paintIcon(null, g, 0, 0);
    g.dispose();
    BufferedImage img = UIUtil.createImage(source.getIconWidth(), source.getIconHeight(), Transparency.TRANSLUCENT);
    int[] rgba = new int[4];
    for (int y = 0; y < src.getRaster().getHeight(); y++) {
        for (int x = 0; x < src.getRaster().getWidth(); x++) {
            src.getRaster().getPixel(x, y, rgba);
            if (rgba[3] != 0) {
                img.getRaster().setPixel(x, y, filter.convert(rgba));
            }
        }
    }
    return createImageIcon(img);
}

75. ShadowBorderPainter#createShadow()

View license
public static Shadow createShadow(Image source, int x, int y, boolean paintSource, int shadowSize) {
    final float w = source.getWidth(null);
    final float h = source.getHeight(null);
    float ratio = w / h;
    float deltaX = shadowSize;
    float deltaY = shadowSize / ratio;
    final Image scaled = source.getScaledInstance((int) (w + deltaX), (int) (h + deltaY), Image.SCALE_SMOOTH);
    final BufferedImage s = GraphicsUtilities.createCompatibleTranslucentImage(scaled.getWidth(null), scaled.getHeight(null));
    final Graphics2D graphics = (Graphics2D) s.getGraphics();
    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    graphics.drawImage(scaled, 0, 0, null);
    final BufferedImage shadow = new ShadowRenderer(shadowSize, .25f, Gray.x00).createShadow(s);
    if (paintSource) {
        final Graphics imgG = shadow.getGraphics();
        final double d = shadowSize * 0.5;
        imgG.drawImage(source, (int) (shadowSize + d), (int) (shadowSize + d / ratio), null);
    }
    return new Shadow(shadow, x - shadowSize - 5, y - shadowSize + 2);
}

76. Win32ShellFolderManager2#getStandardViewButton()

View license
private static Image getStandardViewButton(int iconIndex) {
    Image result = STANDARD_VIEW_BUTTONS[iconIndex];
    if (result != null) {
        return result;
    }
    BufferedImage img = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
    img.setRGB(0, 0, 16, 16, Win32ShellFolder2.getStandardViewButton0(iconIndex), 0, 16);
    STANDARD_VIEW_BUTTONS[iconIndex] = img;
    return img;
}

77. PrintAllXcheckJNI#main()

Project: jdk7u-jdk
Source File: PrintAllXcheckJNI.java
View license
public static void main(String[] s) {
    Frame frame = new Frame();
    frame.setVisible(true);
    BufferedImage img = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D g = img.createGraphics();
    frame.printAll(g);
    g.dispose();
    img.flush();
}

78. OpCompatibleImageTest#doTest()

View license
public void doTest(int type) {
    System.out.println("Test for type " + describeType(type));
    BufferedImage src = createTestImage(type);
    BufferedImage res = null;
    System.out.println("Testing null destination...");
    try {
        res = op.filter(src, null);
    } catch (ImagingOpException e) {
        throw new RuntimeException("Test FAILED!", e);
    }
    if (res == null || ((src.getType() != BufferedImage.TYPE_BYTE_INDEXED) && (res.getType() != src.getType()))) {
        throw new RuntimeException("Test FAILED!");
    }
    System.out.println("Test PASSED.");
}

79. SingleArrayTest#doTest()

Project: jdk7u-jdk
Source File: SingleArrayTest.java
View license
public void doTest(int bi_type) {
    System.out.println("Test for type: " + bi_type);
    BufferedImage src = new BufferedImage(2, 2, bi_type);
    BufferedImage dst = new BufferedImage(2, 2, bi_type);
    doTest(src.getData(), dst.getRaster());
    doTest(src, dst);
    System.out.println("Test passed.");
}

80. EncodeSubImageTest#main()

Project: jdk7u-jdk
Source File: EncodeSubImageTest.java
View license
public static void main(String[] args) throws IOException {
    if (args.length > 0) {
        format = args[0];
    }
    writer = ImageIO.getImageWritersByFormatName(format).next();
    file_suffix = writer.getOriginatingProvider().getFileSuffixes()[0];
    BufferedImage src = createTestImage();
    EncodeSubImageTest m1 = new EncodeSubImageTest(src);
    m1.doTest("test_src");
    BufferedImage sub = src.getSubimage(subImageOffset, subImageOffset, src.getWidth() - 2 * subImageOffset, src.getHeight() - 2 * subImageOffset);
    EncodeSubImageTest m2 = new EncodeSubImageTest(sub);
    m2.doTest("test_sub");
}

81. LUTCompareTest#createTestImage()

Project: jdk7u-jdk
Source File: LUTCompareTest.java
View license
/* Create test image with two frames:
     *  1) with {red, red} palette
     *  2) with {blue, red } palette
     */
private static Image createTestImage() throws IOException {
    BufferedImage frame1 = createFrame(new int[] { 0xffff0000, 0xffff0000 });
    BufferedImage frame2 = createFrame(new int[] { 0xff0000ff, 0xffff0000 });
    ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(new File("lut_test.gif"));
    ImageWriteParam param = writer.getDefaultWriteParam();
    writer.setOutput(ios);
    writer.prepareWriteSequence(null);
    writer.writeToSequence(new IIOImage(frame1, null, null), param);
    writer.writeToSequence(new IIOImage(frame2, null, null), param);
    writer.endWriteSequence();
    writer.reset();
    writer.dispose();
    ios.flush();
    ios.close();
    return Toolkit.getDefaultToolkit().createImage("lut_test.gif");
}

82. ColConvCCMTest#testImage()

Project: jdk7u-jdk
Source File: ColConvCCMTest.java
View license
static boolean testImage(int dataType, int rBits, int gBits, int bBits, int cs, BufferedImage gldImage, double accuracy) {
    BufferedImage src = ImageFactory.createCCMImage(cs, dataType);
    BufferedImage dst = ImageFactory.createDstImage(BufferedImage.TYPE_INT_RGB);
    ColorConvertOp op = new ColorConvertOp(null);
    op.filter(src, dst);
    ImageComparator cmp = new ImageComparator(accuracy, rBits, gBits, bBits);
    boolean result = cmp.compare(gldImage, dst);
    if (!result) {
        System.err.println(cmp.getStat());
    }
    return result;
}

83. ColConvDCMTest#testImage()

Project: jdk7u-jdk
Source File: ColConvDCMTest.java
View license
static boolean testImage(int type, int rBits, int gBits, int bBits, int cs, BufferedImage gldImage, double accuracy) {
    BufferedImage src = ImageFactory.createDCMImage(type, cs);
    BufferedImage dst = ImageFactory.createDstImage(BufferedImage.TYPE_INT_RGB);
    ColorConvertOp op = new ColorConvertOp(null);
    op.filter(src, dst);
    ImageComparator cmp = new ImageComparator(accuracy, rBits, gBits, bBits);
    boolean result = cmp.compare(gldImage, dst);
    if (!result) {
        System.err.println(cmp.getStat());
    }
    return result;
}

84. TerminalPanel#establishFontMetrics()

Project: jediterm
Source File: TerminalPanel.java
View license
private void establishFontMetrics() {
    final BufferedImage img = createBufferedImage(1, 1);
    final Graphics2D graphics = img.createGraphics();
    graphics.setFont(myNormalFont);
    final float lineSpace = mySettingsProvider.getLineSpace();
    final FontMetrics fo = graphics.getFontMetrics();
    myDescent = fo.getDescent();
    myCharSize.width = fo.charWidth('W');
    myCharSize.height = fo.getHeight() + (int) (lineSpace * 2);
    myDescent += lineSpace;
    myMonospaced = isMonospaced(fo);
    if (!myMonospaced) {
        LOG.info("WARNING: Font " + myNormalFont.getName() + " is non-monospaced");
    }
    img.flush();
    graphics.dispose();
}

85. MipMapGenerator#resizeToPowerOf2()

Project: jmonkeyengine
Source File: MipMapGenerator.java
View license
public static void resizeToPowerOf2(Image image) {
    BufferedImage original = ImageToAwt.convert(image, false, true, 0);
    int potWidth = FastMath.nearestPowerOfTwo(image.getWidth());
    int potHeight = FastMath.nearestPowerOfTwo(image.getHeight());
    int potSize = Math.max(potWidth, potHeight);
    BufferedImage scaled = scaleDown(original, potSize, potSize);
    AWTLoader loader = new AWTLoader();
    Image output = loader.load(scaled, false);
    image.setWidth(potSize);
    image.setHeight(potSize);
    image.setDepth(0);
    image.setData(output.getData(0));
    image.setFormat(output.getFormat());
    image.setMipMapSizes(null);
}

86. Filtering#moveRGB()

Project: jpexs-decompiler
Source File: Filtering.java
View license
private static int[] moveRGB(int width, int height, int[] rgb, double deltaX, double deltaY, Color fill) {
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    setRGB(img, width, height, rgb);
    BufferedImage retImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = (Graphics2D) retImg.getGraphics();
    g.setPaint(fill);
    g.fillRect(0, 0, width, height);
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.setTransform(AffineTransform.getTranslateInstance(deltaX, deltaY));
    g.setComposite(AlphaComposite.Src);
    g.drawImage(img, 0, 0, null);
    return getRGB(retImg);
}

87. SerializableImage#getComatibleBufferedImage()

View license
public BufferedImage getComatibleBufferedImage() {
    BufferedImage img = getBufferedImage();
    if (GraphicsEnvironment.isHeadless()) {
        //No GUI, no compatible image
        return img;
    }
    GraphicsConfiguration conf = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
    if (img.getColorModel().equals(conf.getColorModel())) {
        return img;
    }
    BufferedImage img2 = conf.createCompatibleImage(img.getWidth(), img.getHeight(), img.getTransparency());
    Graphics2D g2d = img2.createGraphics();
    g2d.drawImage(img, 0, 0, null);
    return img2;
}

88. ImageUtils#zoomImage()

Project: lemon
Source File: ImageUtils.java
View license
public static void zoomImage(InputStream inputStream, OutputStream outputStream, int toWidth, int toHeight) throws Exception {
    BufferedImage bufferedImage = ImageIO.read(inputStream);
    bufferedImage = zoomImage(bufferedImage, toWidth, toHeight);
    BufferedImage outImage = bufferedImage;
    ImageIO.write(outImage, "png", outputStream);
    inputStream.close();
    outputStream.flush();
}

89. LGraphics#drawRGB()

Project: LGame
Source File: LGraphics.java
View license
public void drawRGB(final int[] rgbData, int offset, int scanlength, int x, int y, int width, int height, boolean processAlpha) {
    if (rgbData == null) {
        return;
    }
    if (width == 0 || height == 0) {
        return;
    }
    BufferedImage buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    buf.setRGB(0, 0, width, height, rgbData, 0, scanlength);
    g2d.drawImage(buf, x, y, null);
}

90. LImage#createRGBImage()

Project: LGame
Source File: LImage.java
View license
public static LImage createRGBImage(int[] rgb, int width, int height, boolean processAlpha) {
    if (rgb == null) {
        throw new NullPointerException();
    }
    if (width <= 0 || height <= 0) {
        throw new IllegalArgumentException();
    }
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    if (!processAlpha) {
        int l = rgb.length;
        int[] rgbAux = new int[l];
        for (int i = 0; i < l; i++) {
            rgbAux[i] = rgb[i] | 0xff000000;
        }
        rgb = rgbAux;
    }
    img.setRGB(0, 0, width, height, rgb, 0, width);
    return new LImage(img);
}

91. LGraphics#drawRGB()

Project: LGame
Source File: LGraphics.java
View license
public void drawRGB(final int[] rgbData, int offset, int scanlength, int x, int y, int width, int height, boolean processAlpha) {
    if (rgbData == null) {
        return;
    }
    if (width == 0 || height == 0) {
        return;
    }
    BufferedImage buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    buf.setRGB(0, 0, width, height, rgbData, 0, scanlength);
    g2d.drawImage(buf, x, y, null);
}

92. LImage#createRGBImage()

Project: LGame
Source File: LImage.java
View license
public static LImage createRGBImage(int[] rgb, int width, int height, boolean processAlpha) {
    if (rgb == null) {
        throw new NullPointerException();
    }
    if (width <= 0 || height <= 0) {
        throw new IllegalArgumentException();
    }
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    if (!processAlpha) {
        int l = rgb.length;
        int[] rgbAux = new int[l];
        for (int i = 0; i < l; i++) {
            rgbAux[i] = rgb[i] | 0xff000000;
        }
        rgb = rgbAux;
    }
    img.setRGB(0, 0, width, height, rgb, 0, width);
    return new LImage(img);
}

93. JavaSEGraphicsUtils#newRGBImage()

Project: LGame
Source File: JavaSEGraphicsUtils.java
View license
public static Image newRGBImage(int[] rgb, int width, int height, boolean processAlpha) {
    if (rgb == null) {
        throw new NullPointerException();
    }
    if (width <= 0 || height <= 0) {
        throw new IllegalArgumentException();
    }
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    if (!processAlpha) {
        int l = rgb.length;
        int[] rgbAux = new int[l];
        for (int i = 0; i < l; i++) {
            rgbAux[i] = rgb[i] | 0xff000000;
        }
        rgb = rgbAux;
    }
    img.setRGB(0, 0, width, height, rgb, 0, width);
    return img;
}

94. GraphicsUtils#newRGBImage()

Project: LGame
Source File: GraphicsUtils.java
View license
public static Image newRGBImage(int[] rgb, int width, int height, boolean processAlpha) {
    if (rgb == null) {
        throw new NullPointerException();
    }
    if (width <= 0 || height <= 0) {
        throw new IllegalArgumentException();
    }
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    if (!processAlpha) {
        int l = rgb.length;
        int[] rgbAux = new int[l];
        for (int i = 0; i < l; i++) {
            rgbAux[i] = rgb[i] | 0xff000000;
        }
        rgb = rgbAux;
    }
    img.setRGB(0, 0, width, height, rgb, 0, width);
    return img;
}

95. DistanceFieldEffect#draw()

Project: libgdx
Source File: DistanceFieldEffect.java
View license
@Override
public void draw(BufferedImage image, Graphics2D g, UnicodeFont unicodeFont, Glyph glyph) {
    BufferedImage input = new BufferedImage(scale * glyph.getWidth(), scale * glyph.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
    drawGlyph(input, glyph);
    DistanceFieldGenerator generator = new DistanceFieldGenerator();
    generator.setColor(color);
    generator.setDownscale(scale);
    // We multiply spread by the scale, so that changing scale will only affect accuracy
    // and not spread in the output image.
    generator.setSpread(scale * spread);
    BufferedImage distanceField = generator.generateDistanceField(input);
    g.drawImage(distanceField, new AffineTransform(), null);
}

96. ColorBleedEffect#processImage()

Project: libgdx
Source File: ColorBleedEffect.java
View license
public BufferedImage processImage(BufferedImage image, int maxIterations) {
    int width = image.getWidth();
    int height = image.getHeight();
    BufferedImage processedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    int[] rgb = image.getRGB(0, 0, width, height, null, 0, width);
    Mask mask = new Mask(rgb);
    int iterations = 0;
    int lastPending = -1;
    while (mask.pendingSize > 0 && mask.pendingSize != lastPending && iterations < maxIterations) {
        lastPending = mask.pendingSize;
        executeIteration(rgb, mask, width, height);
        iterations++;
    }
    processedImage.setRGB(0, 0, width, height, rgb, 0, width);
    return processedImage;
}

97. HashingTest#testHashing()

Project: LIRE
Source File: HashingTest.java
View license
public void testHashing() throws IOException {
    String file1 = "./wang-1000/0.jpg";
    String file2 = "./wang-1000/400.jpg";
    CEDD cedd = new CEDD();
    BufferedImage image = ImageIO.read(new FileInputStream(file1));
    cedd.extract(image);
    System.out.println("hash = " + getHash(cedd));
    image = ImageUtils.scaleImage(image, 200);
    CEDD cedd2 = new CEDD();
    cedd2.extract(image);
    System.out.println(cedd.getDistance(cedd2));
    System.out.println("hash = " + getHash(cedd2));
    CEDD cedd3 = new CEDD();
    BufferedImage image3 = ImageIO.read(new FileInputStream(file2));
    cedd3.extract(image3);
    System.out.println(cedd.getDistance(cedd3));
    System.out.println("hash = " + getHash(cedd3));
}

98. MserTest#testFaulty()

Project: LIRE
Source File: MserTest.java
View license
public void testFaulty() throws IOException {
    MSERDocumentBuilder builder = new MSERDocumentBuilder();
    //        String file = "C:\\Temp\\testImagelogos\\xml\\00\\00\\72330000.gif";
    String file = "C:\\Temp\\test.png";
    BufferedImage image = ImageUtils.createWorkingCopy(ImageIO.read(new FileInputStream(file)));
    BufferedImage image1 = ImageUtils.getGrayscaleImage(image);
    // extract features from image:
    MSER extractor = new MSER();
    List<MSERFeature> features = extractor.computeMSERFeatures(image1);
    ImageUtils.invertImage(image1);
    // invert grey
    features.addAll(extractor.computeMSERFeatures(image1));
    System.out.println(features.size());
}

99. LuminanceLayout#extract()

Project: LIRE
Source File: LuminanceLayout.java
View license
@Override
public void extract(BufferedImage bimg) {
    BufferedImage gray = grayscale.filter(bimg, null);
    // contrast enhancement didn't go to well with the wang 1000 data set.
    //        enhanceContrast(gray);
    BufferedImage small = new BufferedImage(sideLength, sideLength, BufferedImage.TYPE_BYTE_GRAY);
    double scale = (double) Math.max(gray.getWidth(), gray.getHeight()) / 32d;
    int w = (int) (gray.getWidth() / scale);
    int h = (int) (gray.getHeight() / scale);
    int x = 0, y = 0;
    if (w < sideLength)
        x = (sideLength - w) / 2;
    if (h < sideLength)
        y = (sideLength - h) / 2;
    small.getGraphics().fillRect(0, 0, sideLength, sideLength);
    //        small.getGraphics().drawImage(gray, 0, 0, 8, 8, null);
    small.getGraphics().drawImage(gray, x, y, w, h, null);
    histogram = new double[sideLength * sideLength];
    small.getRaster().getPixels(0, 0, sideLength, sideLength, histogram);
    for (int i = 0; i < histogram.length; i++) {
        // quantize colors to 32 steps ...
        histogram[i] = Math.floor(histogram[i] / 8d);
    }
//        histogram = jpgDct(histogram);
}

100. FNCCTest#main()

Project: lookup
Source File: FNCCTest.java
View license
public static void main(String[] args) {
    BufferedImage image = Capture.load(OCRTest.class, "cyclopst1.png");
    BufferedImage template = Capture.load(OCRTest.class, "cyclopst3.png");
    // rgb image lookup
    {
        List<GPoint> pp = FNCC.lookupAll(new ImageBinaryRGB(image), new ImageBinaryRGBFeature(template, 5000), 0.9f);
        for (GPoint p : pp) {
            System.out.println(p);
        }
    }
    // grey image lookup
    {
        List<GPoint> pp = FNCC.lookupAll(new ImageBinaryGrey(image), new ImageBinaryRGBFeature(template, 5000), 0.9f);
        for (GPoint p : pp) {
            System.out.println(p);
        }
    }
}