java.awt.image.BufferedImage#getSubimage()源码实例Demo

下面列出了java.awt.image.BufferedImage#getSubimage() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: RipplePower   文件: ImageSet.java
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]);
	}

}
 
源代码2 项目: Knowage-Server   文件: PdfCreator.java
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;
}
 
源代码3 项目: GIFKR   文件: PerspectiveFilter.java
@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;
}
 
源代码4 项目: dragonwell8_jdk   文件: ColConvCCMTest.java
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;
}
 
源代码5 项目: NetDiscovery   文件: SeleniumUtils.java
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();
        }
    }
 
源代码6 项目: jdk8u60   文件: ColConvCCMTest.java
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;
}
 
源代码7 项目: StormCV   文件: TilingOp.java
@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;
}
 
源代码8 项目: NetDiscovery   文件: SeleniumUtils.java
/**
 * 截取某个区域的截图
 * @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();
    }
}
 
源代码9 项目: SikuliX1   文件: Tracker.java
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();
   }
}
 
源代码10 项目: runelite   文件: InstanceMapOverlay.java
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;
}
 
源代码11 项目: SVG-Android   文件: AssetUtil.java
/**
 * 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);
}
 
源代码12 项目: hifive-pitalium   文件: ScrollBorderElementTest.java
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)));
		}
	}
}
 
源代码13 项目: ServerListPlus   文件: FaviconHelper.java
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);
}
 
源代码14 项目: MtgDesktopCompanion   文件: ImageTools.java
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);
}
 
源代码15 项目: hermes   文件: Images.java
/**
 * 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);
	}

}
 
源代码16 项目: mappwidget   文件: Cutter.java
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");

		}
	}
}
 
源代码17 项目: WorldGrower   文件: SwingUtils.java
private static BufferedImage cropImage(BufferedImage src, int width, int height) {
	BufferedImage dest = src.getSubimage(0, 0, width, height);
	return dest;
}
 
源代码18 项目: selenium-shutterbug   文件: ImageProcessor.java
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);
}
 
源代码19 项目: super-cloudops   文件: ImageTailor.java
/**
 * 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;
}
 
源代码20 项目: hifive-pitalium   文件: ImageUtils.java
/**
 * 全体画像の中に指定した部分画像が含まれているかどうかを取得します。
 *
 * @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;
}