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

The following are Jave code examples for showing how to use getSubimage() of the java.awt.image.BufferedImage class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: GIFKR   File: PerspectiveFilter.java   View Source Code Vote up 6 votes
@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 2
Project: BatBat-Game   File: TopLeftPiece.java   View Source Code Vote up 6 votes
public TopLeftPiece(TileMap tm) {
	super(tm);
	try {	
		BufferedImage spritesheet = ImageIO.read(
			getClass().getResourceAsStream("/Sprites/Other/ballBatBoss.gif")
		);
		sprites = new BufferedImage[1];
		width = height = 4;
		sprites[0] = spritesheet.getSubimage(0, 0, 10, 10);
		animation.setFrames(sprites);
		animation.setDelay(-1);
	}
	catch(Exception e) {
		e.printStackTrace();
	}
}
 
Example 3
Project: opentest   File: ImageFinder.java   View Source Code Vote up 6 votes
@Override
public ImageFinderResult findImage(BufferedImage sourceImage, Rectangle sourceRect, BufferedImage templateImage, double desiredAccuracy) {
    BufferedImage subImage = sourceImage;
    if (sourceRect != null) {
        subImage = sourceImage.getSubimage(
                sourceRect.x,
                sourceRect.y,
                sourceRect.width,
                sourceRect.height);
    }

    Mat sourceMat = CvHelper.convertToMat(subImage);
    Mat templateMat = CvHelper.convertToMat(templateImage);

    return this.findImage(sourceMat, templateMat, desiredAccuracy);
}
 
Example 4
Project: StegoProxy   File: PhotoNetRandomPNG.java   View Source Code Vote up 6 votes
/**
 * @param params contains image resolution in int format in first two elements
 */
@Override
public Container createContainer(String[] params) throws IOException {
    BufferedImage image = getImage();
    if (params.length >= 2) {
        int w = Integer.parseInt(params[0]);
        int h = Integer.parseInt(params[1]);

        do {
            if (w > image.getWidth() || h > image.getHeight()) {
                image = getImage();
                continue;
            }

            int startX = r.nextInt(image.getWidth() - w);
            int startY = r.nextInt(image.getHeight() - h);

            image = image.getSubimage(startX, startY, w, h);
            break;
        } while (true);
    }

    return new LosslessImageContainer(image);
}
 
Example 5
Project: BatBat-Game   File: BottomLeftPiece.java   View Source Code Vote up 6 votes
public BottomLeftPiece(TileMap tm) {
	super(tm);
	try {	
		BufferedImage spritesheet = ImageIO.read(
			getClass().getResourceAsStream("/Sprites/Other/ballBatBoss.gif")
		);
		sprites = new BufferedImage[1];
		width = height = 4;
		sprites[0] = spritesheet.getSubimage(0, 10, 10, 10);
		animation.setFrames(sprites);
		animation.setDelay(-1);
	}
	catch(Exception e) {
		e.printStackTrace();
	}
}
 
Example 6
Project: OutsourcedProject   File: ImageUtil.java   View Source Code Vote up 6 votes
/**
 * 实现缩放后的截图
 *
 * @param image          缩放后的图像
 * @param subImageBounds 要截取的子图的范围
 * @param subImageFile   要保存的文件
 * @throws IOException
 */
private static void saveSubImage(BufferedImage image,
                                 Rectangle subImageBounds, File subImageFile) throws IOException {
    if (subImageBounds.x < 0 || subImageBounds.y < 0
            || subImageBounds.width - subImageBounds.x > image.getWidth()
            || subImageBounds.height - subImageBounds.y > image.getHeight()) {
        System.out.println("Bad   subimage   bounds");
        return;
    }
    BufferedImage subImage = image.getSubimage(subImageBounds.x,
            subImageBounds.y, subImageBounds.width, subImageBounds.height);
    String fileName = subImageFile.getName();
    String formatName = fileName.substring(fileName.lastIndexOf('.') + 1);
    ImageIO.write(subImage, formatName, subImageFile);
}
 
Example 7
Project: VTerminal   File: FontLoader.java   View Source Code Vote up 6 votes
/**
 * Processes a font sprite sheet and character data into a usable HashMap of
 * character sprites.
 *
 * @param spriteSheet
 *         The sprite sheet.
 *
 * @param characterData
 *         The character data.
 *
 * @return
 *         The HashMap of character sprites.
 *
 * @throws NullPointerException
 *         If the sprite sheet or character data is null.
 */
private static HashMap<Character, BufferedImage> processFontData(final @NonNull BufferedImage spriteSheet, final @NonNull List<String> characterData) {
    final HashMap<Character, BufferedImage> hashMap = new HashMap<>(characterData.size());

    for (final String string : characterData) {
        if (string.isEmpty() == false) {
            final Scanner scanner = new Scanner(string);
            final char character = (char) scanner.nextInt();

            final int x = scanner.nextInt();
            final int y = scanner.nextInt();
            final int width = scanner.nextInt();
            final int height = scanner.nextInt();
            final BufferedImage image = spriteSheet.getSubimage(x, y, width, height);

            hashMap.put(character, image);
        }
    }

    return hashMap;
}
 
Example 8
Project: GIFKR   File: ImageTools.java   View Source Code Vote up 6 votes
public static BufferedImage fitWidth(BufferedImage img, int width, int height, boolean fast){
	img=resize(img, width, (int)(img.getHeight()*(width/(double)img.getWidth())), fast);
	if(img.getHeight()>height)
		img=img.getSubimage(0, (img.getHeight()-height)/2, img.getWidth(), height);

	BufferedImage fullImage=new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
	Graphics2D g=(Graphics2D)fullImage.getGraphics();
	if(!fast){
		g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
	}
	g.drawImage(img, 0, (height-img.getHeight())/2, null);

	g.dispose();

	return fullImage;	
}
 
Example 9
Project: GIFKR   File: ImageTools.java   View Source Code Vote up 6 votes
public static BufferedImage fitHeight(BufferedImage img, int width, int height, boolean fast){
	img=resize(img, (int)(img.getWidth()*(height/(double)img.getHeight())), height, fast);
	if(img.getHeight()>height){
		img=img.getSubimage((img.getWidth()-width)/2, 0, width, img.getHeight());
	}

	BufferedImage fullImage=new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
	Graphics2D g=(Graphics2D)fullImage.getGraphics();
	if(!fast){
		g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
	}
	g.drawImage(img, (width-img.getWidth())/2, 0, null);

	g.dispose();

	return fullImage;	
}
 
Example 10
Project: GlitchKernel   File: DataAsSound.java   View Source Code Vote up 5 votes
@Override
public byte[] glitchPixels(byte[] inputImageBytes) throws Exception 
{
	int audioBitRate = ((Integer) getPixelGlitchParameters().get("bitRateBlend")).intValue();
	float bitRateBlend = (float) audioBitRate / 10;
	if(bitRateBlend < 0.1F || bitRateBlend > 0.9F)
	{
		return null;
	}
	
	BufferedImage inputImage = ImageUtil.getImageFromBytes(inputImageBytes);
	InputStream imageInputStream = new ByteArrayInputStream(inputImageBytes);
	AudioInputStream distortionAudioStream = new AudioInputStream(imageInputStream, new AudioFormat(AudioFormat.Encoding.ULAW, ThreadLocalRandom.current().nextInt(8000,  20000), 8, 5, 9, ThreadLocalRandom.current().nextInt(8000,  20000), true), inputImageBytes.length);
	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	AudioSystem.write(distortionAudioStream, Type.WAVE, outputStream);
	BufferedImage outputImage = new BufferedImage(inputImage.getWidth(), inputImage.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
	byte[] imageData = ((DataBufferByte) outputImage.getRaster().getDataBuffer()).getData();
	System.arraycopy(outputStream.toByteArray(),0,imageData,0,outputStream.toByteArray().length);
	int[] abgrOffsets = {3, 2, 1, 0}; 
	DataBuffer outputBuffer = new DataBufferByte(imageData, imageData.length);
    WritableRaster raster = Raster.createInterleavedRaster(outputBuffer, inputImage.getWidth(), inputImage.getHeight(), 4 * inputImage.getWidth(), 4, abgrOffsets, null);
    ColorModel colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE);
    BufferedImage rasterizedImage = new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null);
    rasterizedImage = resizeImage(rasterizedImage, inputImage.getWidth() * 4, inputImage.getHeight() * 4);
    Graphics2D g2d = rasterizedImage.createGraphics();
    g2d.setComposite(AlphaComposite.SrcOver.derive(bitRateBlend));
    g2d.drawImage(inputImage, 0, 0, null);
    g2d.dispose();
    rasterizedImage = rasterizedImage.getSubimage(0, 0, inputImage.getWidth(), inputImage.getHeight());
	return ImageUtil.getImageBytes(rasterizedImage);
}
 
Example 11
Project: Svg2AndroidXml   File: AssetUtil.java   View Source Code Vote up 5 votes
/**
 * Applies a gaussian blur of the given radius to the given {@link BufferedImage} using a kernel
 * convolution.
 *
 * @param source The source image.
 * @param radius The blur radius, in pixels.
 * @return A new, blurred image, or the source image if no blur is performed.
 */
public static BufferedImage blurredImage(BufferedImage source, double radius) {
    if (radius == 0) {
        return source;
    }
    final int r = (int) Math.ceil(radius);
    final int rows = r * 2 + 1;
    final float[] kernelData = new float[rows * rows];
    final double sigma = radius / 3;
    final double sigma22 = 2 * sigma * sigma;
    final double sqrtPiSigma22 = Math.sqrt(Math.PI * sigma22);
    final double radius2 = radius * radius;
    double total = 0;
    int index = 0;
    double distance2;
    int x, y;
    for (y = -r; y <= r; y++) {
        for (x = -r; x <= r; x++) {
            distance2 = 1.0 * x * x + 1.0 * y * y;
            if (distance2 > radius2) {
                kernelData[index] = 0;
            } else {
                kernelData[index] = (float) (Math.exp(-distance2 / sigma22) / sqrtPiSigma22);
            }
            total += kernelData[index];
            ++index;
        }
    }
    for (index = 0; index < kernelData.length; index++) {
        kernelData[index] /= total;
    }
    // We first pad the image so the kernel can operate at the edges.
    BufferedImage paddedSource = paddedImage(source, r);
    BufferedImage blurredPaddedImage = operatedImage(paddedSource, new ConvolveOp(
            new Kernel(rows, rows, kernelData), ConvolveOp.EDGE_ZERO_FILL, null));
    return blurredPaddedImage.getSubimage(r, r, source.getWidth(), source.getHeight());
}
 
Example 12
Project: Azmata   File: SpriteSheet.java   View Source Code Vote up 5 votes
/**
 * Constructs and returns the sprites in the sprite sheet
 *
 * @return The sprites in the sprite sheet
 */
public Image[][] sprites() {
    if (sprites == null) {
        sprites = new Image[4][3];
        BufferedImage sheet = Azmata.imageFromFile(sheet_path);
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 3; j++) {
                sprites[i][j] = sheet.getSubimage(j * Azmata.BLOCK_SIZE, i * Azmata.BLOCK_SIZE, Azmata.BLOCK_SIZE, Azmata.BLOCK_SIZE);
            }
        }
    }
    return sprites;
}
 
Example 13
Project: jmonet   File: AbstractSelectionTool.java   View Source Code Vote up 5 votes
/**
 * Make the canvas image bounded by the given selection shape the current selected image.
 */
protected void getSelectionFromCanvas() {
    getCanvas().clearScratch();

    Shape selectionBounds = getSelectionOutline();
    BufferedImage maskedSelection = maskSelection(getCanvas().getCanvasImage(), selectionBounds);
    BufferedImage trimmedSelection = maskedSelection.getSubimage(selectionBounds.getBounds().x, selectionBounds.getBounds().y, selectionBounds.getBounds().width, selectionBounds.getBounds().height);

    selectedImage.set(trimmedSelection);
    redrawSelection();
}
 
Example 14
Project: NapBot   File: NapchartHandler.java   View Source Code Vote up 5 votes
static synchronized File downloadNapchart(String chart, File f) throws IOException
{
	if (f.exists())
	{
		charts.add(chart);
		return f;
	}
	else
	{
		try
		{
			/*
			driver.get("https://napchart.com/" + chart);
			File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
			*/
			File screenshot = File.createTempFile("napchart", "png");
			FileUtils.copyURLToFile(new URL("https://napchart.com/api/getImage?chartid=" + chart + "&width=600&height=600&shape=circle"), screenshot);
			BufferedImage image = ImageIO.read(screenshot);
			screenshot.delete();
			/*
			WebElement canvas = driver.findElement(By.className("canvas"));
			Point canvasLocation = canvas.getLocation();
			int canvasWidth = canvas.getSize().getWidth();
			int canvasHeight = canvas.getSize().getHeight();
			BufferedImage eleScreenshot = image.getSubimage(canvasLocation.getX(), canvasLocation.getY(), canvasWidth, canvasHeight);
			*/
			BufferedImage eleScreenshot = image.getSubimage(20, 0, 560, 600); // slight edge crop
			ImageIO.write(eleScreenshot, "png", f);
			charts.add(chart);
		}
		catch (Throwable t)
		{
			throw new IOException("Failed to download image from napchart.com", t);
		}
	}
	return f;
}
 
Example 15
Project: willtest   File: FixedTopBarShootingStrategy.java   View Source Code Vote up 5 votes
@Override
public BufferedImage getScreenshot(WebDriver wd) {
    if(Objects.nonNull(topElementToRemove)) {
        calculateHeaderSizeToCut(wd);
    }
    JavascriptExecutor js = (JavascriptExecutor) wd;

    int allH = getFullHeight(wd);
    int allW = getFullWidth(wd);
    int winH = getWindowHeight(wd);

    winH = winH - headerToCut;
    int scrollTimes = allH / winH;
    int tail = allH - winH * scrollTimes;

    BufferedImage finalImage = new BufferedImage(allW, allH, BufferedImage.TYPE_4BYTE_ABGR);
    Graphics2D graphics = finalImage.createGraphics();

    js.executeScript("scroll(0, arguments[0])", 0);
    BufferedImage firstPart = simple().getScreenshot(wd);
    graphics.drawImage(firstPart, 0, 0, null);

    for (int n = 1; n < scrollTimes; n++) {
        js.executeScript("scroll(0, arguments[0])", winH * n);
        BufferedImage part = getHeaderCutImage(wd);
        graphics.drawImage(part, 0, n * winH + headerToCut, null);
    }

    if (tail > 0) {
        js.executeScript("scroll(0, document.body.scrollHeight)");
        BufferedImage last = getHeaderCutImage(wd);
        BufferedImage tailImage = last.getSubimage(0, last.getHeight() - tail, last.getWidth(), tail);
        graphics.drawImage(tailImage, 0, scrollTimes * winH, null);
    }
    graphics.dispose();

    return finalImage;
}
 
Example 16
Project: GIFKR   File: ImageTools.java   View Source Code Vote up 5 votes
public static BufferedImage unrotate(BufferedImage img, double angle, int origw, int origh, boolean subpixel, boolean fast) {

		img = rotate(img, 360 - (angle % 360), fast);

		int startx = (img.getWidth()-origw)/2;
		int starty = (img.getHeight()-origh)/2;

		int extra = (img.getWidth() - origw) >2 ? 1 : 0;

		img = img.getSubimage(startx, starty, origw + extra, origh + extra);

		AffineTransform t = new AffineTransform();

		if(subpixel) {
			double xerr = 0, yerr = 0;
			for(int x = 0; x < img.getWidth(); x++)
				xerr += ImageTools.getAlpha(img.getRGB(x, 0));
			for(int y = 0; y < img.getHeight(); y++)
				yerr += ImageTools.getAlpha(img.getRGB(0, y));

			xerr /= (img.getWidth() * 255);
			xerr = 1 - xerr;
			yerr /= (img.getHeight() * 255);
			yerr = 1 - yerr;
			t.translate(-yerr, -xerr);
		}

		BufferedImage ret = new BufferedImage(origw, origh, BufferedImage.TYPE_INT_ARGB);
		Graphics2D g = ret.createGraphics();
		g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
		g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

		g.drawImage(img, t, null);
		g.dispose();

		return ret;
	}
 
Example 17
Project: PekaED   File: PK2Sprite.java   View Source Code Vote up 4 votes
private void loadBufferedImage() {
	try {
		BufferedImage tilesheet = ImageIO.read(new File(Settings.SPRITE_PATH + cleanString(imageFile)));
		
		try {
			image = tilesheet.getSubimage(frameX, frameY, frameWidth, frameHeight);
		} catch (Exception ex) {
			System.out.println(filename + " - " + frameX + ", " + frameY + " - " + frameWidth + " - " + frameHeight);
		}
			
		BufferedImage result = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
		 
	    // make color transparent
	    int oldRGB = new Color(148, 209, 222).getRGB();
	    int oldRGB2 = new Color(128, 205, 214).getRGB();
	    int oldRGB3 = new Color(155, 232, 224).getRGB();
	    int oldRGB4 = new Color(114, 200, 228).getRGB();
	 
	    for (int i = 0; i < image.getWidth(); i++) {
	    	for (int j = 0; j < image.getHeight(); j++) {
	    		if (image.getRGB(i, j) != oldRGB && image.getRGB(i, j) != oldRGB2 && image.getRGB(i, j) != oldRGB3 && image.getRGB(i, j) != oldRGB4) {
	    			result.setRGB(i, j, image.getRGB(i, j));
	    		}
	    	}
	    }
	    
	   if (color != 255) {
		  /*
		   * if (this->vari != VARI_NORMAALI){ //Change sprite colors
				PisteDraw2_Image_GetSize(bufferi,w,h);
		
				PisteDraw2_DrawImage_Start(bufferi,*&buffer,leveys);
		
				for (x=0;x<w;x++)
					for (y=0;y<h;y++)
						if ((vari = buffer[x+y*leveys]) != 255){
							vari %= 32;
							vari += this->vari;
							buffer[x+y*leveys] = vari;
						}
		
				PisteDraw2_DrawImage_End(bufferi);
			}
			
			TODO Tint sprite
		   */
	   }
	    
	    image = result;
	} catch (IOException e) {
		//e.printStackTrace();
	}
}
 
Example 18
Project: imageio-jnr   File: TurboJpegImageReader.java   View Source Code Vote up 4 votes
@Override
public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException {
  checkIndex(imageIndex);
  ByteBuffer data = jpegData;
  try {
    int rotation = 0;
    Rectangle region = null;
    Rectangle extraCrop = null;
    if (param instanceof TurboJpegImageReadParam) {
      rotation = ((TurboJpegImageReadParam) param).getRotationDegree();
    }
    if (param != null && param.getSourceRegion() != null) {
      region = param.getSourceRegion();
      scaleRegion(imageIndex, region);
      if (region.x + region.width == getWidth(0)) {
        region.width = 0;
      }
      if (region.y + region.height == getHeight(0)) {
        region.height = 0;
      }
      if (!isRegionFullImage(imageIndex, region)) {
        extraCrop = adjustRegion(info.getMCUSize(), region, rotation);
      } else {
        region = null;
      }
    }
    if (region != null || rotation != 0) {
      data = lib.transform(data.array(), info, region, rotation);
    }
    Info transformedInfo = lib.getInfo(data.array());
    BufferedImage img = lib.decode(
        data.array(), transformedInfo, transformedInfo.getAvailableSizes().get(imageIndex));
    if (extraCrop != null) {
      adjustExtraCrop(imageIndex, transformedInfo, extraCrop);
      img = img.getSubimage(extraCrop.x, extraCrop.y, extraCrop.width, extraCrop.height);
    }
    return img;
  } catch (TurboJpegException e) {
    throw new IOException(e);
  }
}
 
Example 19
Project: willtest   File: FixedTopBarShootingStrategy.java   View Source Code Vote up 4 votes
private BufferedImage getHeaderCutImage(WebDriver webDriver) {
    BufferedImage baseImage = simple().getScreenshot(webDriver);
    int h = baseImage.getHeight();
    int w = baseImage.getWidth();
    return baseImage.getSubimage(0, headerToCut, w, h - headerToCut);
}
 
Example 20
Project: Lunar   File: SpriteManager.java   View Source Code Vote up 2 votes
/**
 * Get a part of the image.
 *
 * @param image  the image
 * @param x      the X coordinate.
 * @param y      the Y coordinate.
 * @param width  the width
 * @param height the height
 * @return the sub section of the image.
 */
public static BufferedImage getSectionAt(BufferedImage image, int x, int y, int width, int height) {
    return image.getSubimage(x, y, width, height);
}