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

The following examples show how to use java.awt.image.BufferedImage#getSubimage() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: RipplePower   File: ImageSet.java    License: Apache License 2.0 6 votes vote down vote up
public void SplitWindow(BufferedImage img) {
	int FrameSize = 6;
	int CornerSize = 14;
	int WholeSize = 64;
	int BorderLength = 8;
	BufferedImage SPLITS[] = new BufferedImage[8];
	SPLITS[0] = img.getSubimage(WholeSize / 2 - BorderLength / 2, 0, BorderLength, FrameSize);
	SPLITS[1] = img.getSubimage(0, WholeSize / 2 - BorderLength / 2, FrameSize, BorderLength);
	SPLITS[2] = img.getSubimage(WholeSize / 2 - BorderLength / 2, WholeSize - FrameSize, BorderLength, FrameSize);
	SPLITS[3] = img.getSubimage(WholeSize - FrameSize, WholeSize / 2 - BorderLength / 2, FrameSize, BorderLength);
	SPLITS[4] = img.getSubimage(0, 0, CornerSize, CornerSize);
	SPLITS[5] = img.getSubimage(0, WholeSize - CornerSize, CornerSize, CornerSize);
	SPLITS[6] = img.getSubimage(WholeSize - CornerSize, WholeSize - CornerSize, CornerSize, CornerSize);
	SPLITS[7] = img.getSubimage(WholeSize - CornerSize, 0, CornerSize, CornerSize);
	for (int i = 0; i < SPLITS.length; i++) {
		BufferedImageHash.put((new StringBuilder("win")).append(i).toString(), SPLITS[i]);
	}

}
 
Example 2
Image cutImage(byte[] bytes, boolean cutImageHeight, boolean cutImageWidth, int tableHeight, int tableWidth, int imgWidth, int imgHeight)
		throws IOException, BadElementException {
	logger.debug("IN");

	BufferedImage image = null; // Read from a file
	BufferedImage region = null;

	int pxWidthToCut = (cutImageWidth == true) ? tableWidth : imgWidth;
	int pxHeightToCut = (cutImageHeight == true) ? tableHeight : imgHeight;

	InputStream inputStream = new ByteArrayInputStream(bytes);

	image = ImageIO.read(inputStream); // Read from an input stream
	try {
		region = image.getSubimage(0, 0, pxWidthToCut, pxHeightToCut);
	} catch (Exception e) {
		e.printStackTrace();
	}
	byte[] newBytes = getBytes(region);
	Image cutImg = Image.getInstance(newBytes);
	// ImageIO.write(region,"PNG",new File("C:/nuovaImmagine222.PNG"));
	logger.debug("OUT");

	return cutImg;
}
 
Example 3
@Override
protected BufferedImage apply(BufferedImage img) {
	
	BufferedImage img2 = new BufferedImage(img.getWidth(), img.getHeight(), img.getType());
	Graphics2D g = img2.createGraphics();
	
	for(int y = 0; y < img.getHeight(); y++) {
		BufferedImage row = img.getSubimage(0, y, img.getWidth(), 1);
		
		int offset = Math.round((y/2f - img.getHeight()/4f) * (2 * shift * img.getWidth()));
		offset = offset % img.getWidth();
		
		g.drawImage(row, offset, y, null);
		g.drawImage(row, (offset < 0 ? 1 : -1) * img.getWidth() + offset, y, null);
	}

	g.dispose();
	
	return img2;
}
 
Example 4
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;
}
 
Example 5
Source Project: NetDiscovery   File: SeleniumUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void taskScreenShot(WebDriver driver,WebElement element,String pathName) {

        //指定了OutputType.FILE做为参数传递给getScreenshotAs()方法,其含义是将截取的屏幕以文件形式返回。
        File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        //利用IOUtils工具类的copyFile()方法保存getScreenshotAs()返回的文件对象。

        try {
            //获取元素在所处frame中位置对象
            Point p = element.getLocation();
            //获取元素的宽与高
            int width = element.getSize().getWidth();
            int height = element.getSize().getHeight();
            //矩形图像对象
            Rectangle rect = new Rectangle(width, height);
            BufferedImage img = ImageIO.read(srcFile);
            BufferedImage dest = img.getSubimage(p.getX(), p.getY(), rect.width, rect.height);
            ImageIO.write(dest, "png", srcFile);
            IOUtils.copyFile(srcFile, new File(pathName));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
Example 6
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;
}
 
Example 7
Source Project: StormCV   File: TilingOp.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<Frame> execute(CVParticle particle) throws Exception {
	List<Frame> result = new ArrayList<Frame>();
	if(!(particle instanceof Frame)) return result;
	
	Frame frame = (Frame) particle;
	BufferedImage image = frame.getImage();
	if(image == null) return result;
	if(image.getWidth()<2*cols || image.getHeight()<2*rows) return result;
	
	int width = image.getWidth() / cols;
	int height = image.getHeight() / rows;
	int tileIndex = 0;
	for(int r=0; r<rows; r++){
		for(int c=0; c<cols; c++){
			Rectangle box = new Rectangle(c*width, r*height, width + pixelOverlap, height + pixelOverlap);
			box = box.intersection(frame.getBoundingBox());
			BufferedImage tile = image.getSubimage(box.x, box.y, box.width, box.height);
			byte[] buffer = ImageUtils.imageToBytes(tile, imageType);
			result.add(new Frame(frame.getStreamId()+"_"+tileIndex, frame.getSequenceNr(), imageType, buffer, frame.getTimestamp(), box));
			tileIndex++;
		}
	}
	return result;
}
 
Example 8
Source Project: NetDiscovery   File: SeleniumUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 截取某个区域的截图
 * @param driver
 * @param x
 * @param y
 * @param width
 * @param height
 * @param pathName
 */
public static void taskScreenShot(WebDriver driver,int x,int y,int width,int height,String pathName) {

    //指定了OutputType.FILE做为参数传递给getScreenshotAs()方法,其含义是将截取的屏幕以文件形式返回。
    File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    //利用IOUtils工具类的copyFile()方法保存getScreenshotAs()返回的文件对象。

    try {
        //矩形图像对象
        Rectangle rect = new Rectangle(width, height);
        BufferedImage img = ImageIO.read(srcFile);
        BufferedImage dest = img.getSubimage(x, y, rect.width, rect.height);
        ImageIO.write(dest, "png", srcFile);
        IOUtils.copyFile(srcFile, new File(pathName));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 9
Source Project: SikuliX1   File: Tracker.java    License: MIT License 6 votes vote down vote up
public Tracker(Guide guide, Pattern pattern, Region match){
   this.guide = guide;
   //this.match = match;
   screen = new Screen();
   BufferedImage image;
   BufferedImage center;
   this.pattern = pattern;
   try {
      image = pattern.getBImage();
      int w = image.getWidth();
      int h = image.getHeight();
      center = image.getSubimage(w/4,h/4,w/2,h/2);
      centerPattern = new Pattern(center);
   } catch (Exception e) {
      e.printStackTrace();
   }
}
 
Example 10
private static BufferedImage minimapToBufferedImage(SpritePixels spritePixels)
{
	int width = spritePixels.getWidth();
	int height = spritePixels.getHeight();
	int[] pixels = spritePixels.getPixels();
	BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
	img.setRGB(0, 0, width, height, pixels, 0, width);
	// 24624 / 512 and 24624 % 512 are both 48
	img = img.getSubimage(48, 48, TILE_SIZE * 104, TILE_SIZE * 104);
	return img;
}
 
Example 11
Source Project: SVG-Android   File: AssetUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Trims the transparent pixels from the given {@link BufferedImage} (returns a sub-image).
 *
 * @param source The source image.
 * @return A new, trimmed image, or the source image if no trim is performed.
 */
public static BufferedImage trimmedImage(BufferedImage source) {
    final int minAlpha = 1;
    final int srcWidth = source.getWidth();
    final int srcHeight = source.getHeight();
    Raster raster = source.getRaster();
    int l = srcWidth, t = srcHeight, r = 0, b = 0;

    int alpha, x, y;
    int[] pixel = new int[4];
    for (y = 0; y < srcHeight; y++) {
        for (x = 0; x < srcWidth; x++) {
            raster.getPixel(x, y, pixel);
            alpha = pixel[3];
            if (alpha >= minAlpha) {
                l = Math.min(x, l);
                t = Math.min(y, t);
                r = Math.max(x, r);
                b = Math.max(y, b);
            }
        }
    }

    if (l > r || t > b) {
        // No pixels, couldn't trim
        return source;
    }

    return source.getSubimage(l, t, r - l + 1, b - t + 1);
}
 
Example 12
private void validateHasBorder() throws Exception {
	BufferedImage image = loadTargetResults("s").get(0).getImage().get();
	int width = image.getWidth();
	int height = image.getHeight();
	int centerX = width / 2;
	int centerY = height / 2;

	// border
	double ratio = getPixelRatio();
	int border = (int) Math.round(5.0 * ratio);
	Color borderColor = Color.valueOf(image.getRGB(0, 0));
	for (int i = 0; i < border; i++) {
		assertThat(Color.valueOf(image.getRGB(i, centerY)), is(borderColor));
		assertThat(Color.valueOf(image.getRGB(width - i - 1, centerY)), is(borderColor));
		assertThat(Color.valueOf(image.getRGB(centerX, i)), is(borderColor));
		assertThat(Color.valueOf(image.getRGB(centerX, height - i - 1)), is(borderColor));
	}

	// contents
	BufferedImage contentImage = image.getSubimage(border, border, width - border * 2, height - border * 2);
	int contentWidth = contentImage.getWidth();
	int contentHeight = contentImage.getHeight();
	for (int x = 0; x < contentWidth; x++) {
		for (int y = 0; y < contentHeight; y++) {
			assertThat(Color.valueOf(contentImage.getRGB(x, y)), is(not(borderColor)));
		}
	}
}
 
Example 13
private static BufferedImage fromSkin(ServerListPlusCore core, URL url, boolean helm) throws IOException {
    BufferedImage skin = fromURL(core, url);
    if (helm && !isSolidColor(skin, HELM_X, HELM_Y, HEAD_SIZE, HEAD_SIZE)) {
        Graphics2D g = skin.createGraphics();
        g.copyArea(HELM_X, HELM_Y, HEAD_SIZE, HEAD_SIZE, HEAD_X - HELM_X, HEAD_Y - HELM_Y);
        g.dispose();
    }

    return skin.getSubimage(HEAD_X, HEAD_Y, HEAD_SIZE, HEAD_SIZE);
}
 
Example 14
public static BufferedImage trimAlpha(BufferedImage img) {
	
	if(img==null)
		return img;
	
    int width = img.getWidth();
    int height = img.getHeight();
    int x0;
    int x1;
    int j;
    int i;

    leftLoop:
        for(i = 0; i < width; i++) {

            for(j = 0; j < height; j++) {
                if(new Color(img.getRGB(i, j), true).getAlpha() != 0)  {
                    break leftLoop;
                }
            }
        }
    x0 = i;
    rightLoop:
        for(i = width-1; i >= 0; i--) {

            for(j = 0; j < height; j++) {
                if(new Color(img.getRGB(i, j), true).getAlpha() != 0) {
                    break rightLoop;
                }
            }
        }
    x1 = i+1;

    return img.getSubimage(x0, 0, x1-x0, height);
}
 
Example 15
Source Project: hermes   File: Images.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Crop an image
 * 
 * @param originalImage
 *            The image file
 * @param to
 *            The destination file
 * @param x1
 *            The new x origin
 * @param y1
 *            The new y origin
 * @param width
 *            The new width
 * @param height
 *            The new height
 * @param imgWidth
 *            The widht of img
 * @param imgHeight
 *            The height of img
 */
public static Map<String, String> crop(MultipartFile originalImage, int x1, int y1, int width, int height, int imgWidth, int imgHeight) {
	try {
		ByteArrayInputStream bais = new ByteArrayInputStream(originalImage.getBytes());
		MemoryCacheImageInputStream mciis = new MemoryCacheImageInputStream(bais);
		BufferedImage source = ImageIO.read(mciis);
		int owidth = source.getWidth();// 图片原始宽度
		int oheight = source.getHeight();// 图片原始长度
		double ratioW = (double) width / imgWidth; // 原始图片与前台图片显示宽度的比例
		double ratioH = (double) height / imgHeight;

		int cutW = (int) (owidth * ratioW);// 裁剪图片的真实宽度
		int cutH = (int) (oheight * ratioH);

		double ratioX = (double) x1 / imgWidth; // x坐标所在位置的比例
		double ratioY = (double) y1 / imgHeight;

		int xo = (int) (owidth * ratioX);// 图片裁剪开始的真实X坐标
		int yo = (int) (oheight * ratioY);
		// crop 图片
		BufferedImage dest = new BufferedImage(cutW, cutH, BufferedImage.TYPE_INT_RGB);
		Image croppedImage = source.getSubimage(xo, yo, cutW, cutH);
		Graphics graphics = dest.getGraphics();
		graphics.setColor(Color.WHITE);
		graphics.fillRect(0, 0, cutW, cutH);
		graphics.drawImage(croppedImage, 0, 0, null);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ImageIO.write(dest, Files.getExt(originalImage.getOriginalFilename()), baos);
		byte[] bytes = baos.toByteArray();
		String avatar_lg = String.format(BASE64, Files.getMimeType(originalImage.getOriginalFilename()), new String(Base64.encodeBase64(bytes)));

		// resize图片
		BufferedImage destResize = new BufferedImage(46, 46, BufferedImage.TYPE_INT_RGB);
		Image resizeImage = croppedImage.getScaledInstance(46, 46, Image.SCALE_SMOOTH);
		Graphics graphicsResize = destResize.getGraphics();
		graphicsResize.setColor(Color.WHITE);
		graphicsResize.fillRect(0, 0, 46, 46);
		graphicsResize.drawImage(resizeImage, 0, 0, null);
		ByteArrayOutputStream baosResize = new ByteArrayOutputStream();
		ImageIO.write(destResize, Files.getExt(originalImage.getOriginalFilename()), baosResize);
		byte[] bytesResize = baosResize.toByteArray();
		String avatar = String.format(BASE64, Files.getMimeType(originalImage.getOriginalFilename()), new String(Base64.encodeBase64(bytesResize)));

		Map<String, String> map = new HashMap<String, String>();
		map.put("avatar_lg", avatar_lg);
		map.put("avatar", avatar);
		return map;
	} catch (Exception e) {
		throw new RuntimeException(e);
	}

}
 
Example 16
Source Project: mappwidget   File: Cutter.java    License: Apache License 2.0 4 votes vote down vote up
private void imageCut(String inFile, String outDir, int tileSize, String mapName, boolean xml, String concut, PointVO pointTopLeft, PointVO pointBottomRight)
{
	String s = "";

	if (!outDir.endsWith(File.separator))
	{
		s = File.separator;
	}

	BufferedImage image = getImage(inFile);

	int w = image.getWidth();
	int h = image.getHeight();

	if (xml)
	{
		ImageXML.createXML(mapName, tileSize, w, h, pointTopLeft, pointBottomRight);
	}

	if (w < tileSize && h < tileSize)
	{
		saveImage(image, "png", outDir + s + concut + "0_0.png");
		return;
	}

	for (int i = 0, k = 0; i < w - 1; i += tileSize, k++)
	{
		for (int j = 0, l = 0; j < h - 1; j += tileSize, l++)
		{
			int tileWidth = tileSize;
			int tileHeight = tileSize;

			if (tileWidth > (w - i - 1))
			{
				tileWidth = w - i - 1;
			}

			if (tileHeight > (h - j - 1))
			{
				tileHeight = h - j - 1;
			}

			BufferedImage part = image.getSubimage(i, j, tileWidth, tileHeight);
			saveImage(part, "png", outDir + s + concut + k + "_" + l + ".png");

		}
	}
}
 
Example 17
private static BufferedImage cropImage(BufferedImage src, int width, int height) {
	BufferedImage dest = src.getSubimage(0, 0, width, height);
	return dest;
}
 
Example 18
Source Project: selenium-shutterbug   File: ImageProcessor.java    License: MIT License 4 votes vote down vote up
public static BufferedImage cropAround(BufferedImage sourceImage, Coordinates coords, int offsetX, int offsetY) {
    return sourceImage.getSubimage(coords.getX() - offsetX, coords.getY() - offsetY, coords.getWidth() + offsetX * 2, coords.getHeight() + offsetY * 2);
}
 
Example 19
Source Project: super-cloudops   File: ImageTailor.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Do processing cut image.
 * 
 * @param sourceImg
 * @return
 * @throws IOException
 */
private TailoredImage doProcess(BufferedImage sourceImg) throws IOException {
	int width = sourceImg.getWidth();
	int height = sourceImg.getHeight();
	// Check maximum effective width height
	isTrue((width <= sourceMaxWidth && height <= sourceMaxHeight),
			String.format("Source image is too big, max limits: %d*%d", sourceMaxWidth, sourceMaxHeight));
	isTrue((width >= sourceMinWidth && height >= sourceMinHeight),
			String.format("Source image is too small, min limits: %d*%d", sourceMinWidth, sourceMinHeight));

	// 创建背景图,TYPE_4BYTE_ABGR表示具有8位RGBA颜色分量的图像(支持透明的BufferedImage),正常取bufImg.getType()
	BufferedImage primaryImg = new BufferedImage(sourceImg.getWidth(), sourceImg.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
	// 创建滑块图
	BufferedImage blockImg = new BufferedImage(sourceImg.getWidth(), sourceImg.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
	// 随机截取的坐标
	int maxX0 = width - blockWidth - (circleR + circleOffset);
	int maxY0 = height - blockHeight;
	int blockX0 = current().nextInt((int) (maxX0 * 0.25), maxX0); // *0.25防止x坐标太靠左
	int blockY0 = current().nextInt(circleR, maxY0); // 从circleR开始是为了防止上边的耳朵显示不全
	// Setup block borders position.
	initBorderPositions(blockX0, blockY0, blockWidth, blockHeight);

	// 绘制生成新图(图片大小是固定,位置是随机)
	drawing(sourceImg, blockImg, primaryImg, blockX0, blockY0, blockWidth, blockHeight);
	// 裁剪可用区
	int cutX0 = blockX0;
	int cutY0 = Math.max((blockY0 - circleR - circleOffset), 0);
	int cutWidth = blockWidth + circleR + circleOffset;
	int cutHeight = blockHeight + circleR + circleOffset;
	blockImg = blockImg.getSubimage(cutX0, cutY0, cutWidth, cutHeight);

	// Add watermark string.
	addWatermarkIfNecessary(primaryImg);

	// 输出图像数据
	TailoredImage img = new TailoredImage();
	// Primary image.
	ByteArrayOutputStream primaryData = new ByteArrayOutputStream();
	ImageIO.write(primaryImg, "PNG", primaryData);
	img.setPrimaryImg(primaryData.toByteArray());

	// Block image.
	ByteArrayOutputStream blockData = new ByteArrayOutputStream();
	ImageIO.write(blockImg, "PNG", blockData);
	img.setBlockImg(blockData.toByteArray());

	// Position
	img.setX(blockX0);
	img.setY(blockY0 - circleR >= 0 ? blockY0 - circleR : 0);
	return img;
}
 
Example 20
Source Project: hifive-pitalium   File: ImageUtils.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 全体画像の中に指定した部分画像が含まれているかどうかを取得します。
 *
 * @param entireImage 全体画像
 * @param partImage 部分画像
 * @return 全体画像の中に部分画像が含まれていればtrue、含まれていなければfalse
 */
public static boolean isContained(BufferedImage entireImage, BufferedImage partImage) {
	// 元画像の積分画像を作成
	double[][] integralImage = calcIntegralImage(entireImage);

	double sumContent = 0;
	Raster r = partImage.getRaster();
	int[] dArray = new int[r.getNumDataElements()];
	for (int x = 0; x < r.getWidth(); x++) {
		for (int y = 0; y < r.getHeight(); y++) {
			sumContent += r.getPixel(x, y, dArray)[0];
		}
	}

	int contentWidth = partImage.getWidth();
	int contentHeight = partImage.getHeight();
	double p0;
	double p1;
	double p2;
	double p3;
	double sumContainer;
	final int yMax = entireImage.getHeight() - partImage.getHeight() + 1;
	final int xMax = entireImage.getWidth() - partImage.getWidth() + 1;
	for (int y = 0; y < yMax; y++) {
		for (int x = 0; x < xMax; x++) {
			p0 = integralImage[y + contentHeight - 1][x + contentWidth - 1];
			p1 = (x == 0) ? 0 : integralImage[y + contentHeight - 1][x - 1];
			p2 = (y == 0) ? 0 : integralImage[y - 1][x + contentWidth - 1];
			p3 = (x == 0 || y == 0) ? 0 : integralImage[y - 1][x - 1];
			sumContainer = p0 - p1 - p2 + p3;

			if (Double.compare(sumContainer, sumContent) == 0) {
				BufferedImage window = entireImage.getSubimage(x, y, contentWidth, contentHeight);
				if (imageEquals(window, partImage)) {
					return true;
				}
			}
		}
	}

	return false;
}