Example usage for java.awt.image BufferedImage getSubimage

List of usage examples for java.awt.image BufferedImage getSubimage

Introduction

In this page you can find the example usage for java.awt.image BufferedImage getSubimage.

Prototype

public BufferedImage getSubimage(int x, int y, int w, int h) 

Source Link

Document

Returns a subimage defined by a specified rectangular region.

Usage

From source file:Main.java

/**
 * Applies a gaussian blur of the given radius to the given {@link BufferedImage} using a kernel
 * convolution./* w  w w . ja  v  a2  s .  c  om*/
 *
 * @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());
}

From source file:org.ednovo.gooru.application.converter.GooruImageUtil.java

public static void cropImage(String path, int x, int y, int width, int height) throws Exception {
    BufferedImage srcImg = ImageIO.read(new File(path));
    srcImg = srcImg.getSubimage(x, y, width, height);
    ImageIO.write(srcImg, PNG, new File(path));
}

From source file:BluemixUtils.java

public static void retriveFaces(ClassifierUnit unit) throws IOException {
    //curl -X POST -F "images_file=@prez.jpg" "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/detect_faces?api_key={api-key}&version=2016-05-20"
    File facesDir = new File(unit.getFolderWithImages() + "_faces");
    facesDir.mkdir();//w  w  w .  j a va2s  .com
    for (File image : new File(unit.getFolderWithImages()).listFiles()) {
        try {
            String command = "D:/curl/curl -X POST -F \"images_file=@" + image.getAbsolutePath()
                    + "\" \"https://gateway-a.watsonplatform.net/visual-recognition/api/v3/detect_faces?api_key={02a6297b759128a71e59e1a97c682826398584b4}&version=2016-05-20\"";
            String res = executeCmdCommand(command);
            FaceDetection s = new Gson().fromJson(res, FaceDetection.class);
            System.out.println(s.getBluemixImages().get(0).getFaces());
            BufferedImage in = ImageIO.read(image);
            for (Face face : s.getBluemixImages().get(0).getFaces()) {
                FaceLocation faceLoc = face.getFaceLocation();
                BufferedImage newIm = in.getSubimage(faceLoc.getLeft(), faceLoc.getTop(), faceLoc.getWidth(),
                        faceLoc.getHeight());
                File outputfile = new File(facesDir + File.separator + image.getName());
                ImageIO.write(newIm, "jpg", outputfile);
            }
        } catch (Exception ex) {
            Logger.getLogger("KrilovUtils.class").fine(ex.getMessage());
        }
    }

}

From source file:com.vaadin.testbench.screenshot.ImageUtil.java

/**
 * Crops the image to the given size starting at (0,0)
 * /*from w w  w .  j  a  v  a  2  s.co  m*/
 * @param image
 *            The image to crop
 * @param width
 *            width in pixels
 * @param height
 *            height in pixels
 */
private static BufferedImage cropImage(BufferedImage image, int width, int height) {
    if (image.getWidth() == width && image.getHeight() == height) {
        return image;
    }
    return image.getSubimage(0, 0, width, height);
}

From source file:com.jaeksoft.searchlib.util.ImageUtils.java

public final static BufferedImage getSubimage(BufferedImage image, int x, int y, int width, int height) {
    if (width > image.getWidth() - x)
        width = image.getWidth() - x;/*from  w w  w  .j  ava2  s . c om*/
    if (height > image.getHeight() - y)
        height = image.getHeight() - y;
    return image.getSubimage(x, y, width, height);
}

From source file:com.silverpeas.thumbnail.control.ThumbnailController.java

protected static void createCropThumbnailFileOnServer(String pathOriginalFile, String pathCropdir,
        String pathCropFile, ThumbnailDetail thumbnail, int thumbnailWidth, int thumbnailHeight) {
    try {/*from   w  ww . ja  v a2  s .c  o m*/
        // Creates folder if not exists
        File dir = new File(pathCropdir);
        if (!dir.exists()) {
            FileFolderManager.createFolder(pathCropdir);
        }
        // create empty file
        File cropFile = new File(pathCropFile);
        if (!cropFile.exists()) {
            cropFile.createNewFile();
        }

        File originalFile = new File(pathOriginalFile);
        BufferedImage bufferOriginal = ImageIO.read(originalFile);
        // crop image
        BufferedImage cropPicture = bufferOriginal.getSubimage(thumbnail.getXStart(), thumbnail.getYStart(),
                thumbnail.getXLength(), thumbnail.getYLength());
        BufferedImage cropPictureFinal = new BufferedImage(thumbnailWidth, thumbnailHeight,
                BufferedImage.TYPE_INT_RGB);
        // Redimensionnement de l'image
        Graphics2D g2 = cropPictureFinal.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g2.drawImage(cropPicture, 0, 0, thumbnailWidth, thumbnailHeight, null);
        g2.dispose();

        // save crop image
        String extension = FilenameUtils.getExtension(originalFile.getName());
        ImageIO.write(cropPictureFinal, extension, cropFile);
    } catch (Exception e) {
        SilverTrace.warn("thumbnail", "ThumbnailController.createThumbnailFileOnServer()",
                "thumbnail_MSG_CREATE_CROP_FILE_KO", "originalFileName=" + thumbnail.getOriginalFileName()
                        + " cropFileName = " + thumbnail.getCropFileName(),
                e);
    }
}

From source file:com.smash.revolance.ui.model.helper.ImageHelper.java

public static BufferedImage cropImage(final BufferedImage img, int x, int y, int w, int h, double xScale,
        double yScale) {
    x = (int) (x * xScale);
    w = (int) (w * xScale);

    y = (int) (y * yScale);
    h = (int) (h * yScale);

    if (img.getHeight() < (y + h)) {
        h = img.getHeight() - y;/*from   w  w w  .j a  v a  2 s.co m*/
    }
    if (img.getWidth() < (x + w)) {
        w = img.getWidth() - x;
    }

    return img.getSubimage(x, y, w, h);
}

From source file:com.tractionsoftware.reshoot.Reshoot.java

private static BufferedImage cropImage(RemoteWebDriver driver, BufferedImage img, Screenshot screenshot) {
    if (screenshot.crop != null) {
        Region crop = screenshot.crop;
        int left = crop.left;
        int top = crop.top;
        int width = crop.width;
        int height = crop.height;

        // retina images will be twice the size, but we want to
        // keep the crop in normal browser coordinates.
        if (isRetina(driver, img)) {
            left *= 2;/*from  w  w w .j  a  v  a 2s  .  c o m*/
            top *= 2;
            width *= 2;
            height *= 2;
        }

        return img.getSubimage(left, top, width, height);
    }
    return img;
}

From source file:Main.java

/**
 * Trims the transparent pixels from the given {@link BufferedImage} (returns a sub-image).
 *
 * @param source The source image.//from   w w w. j  a v  a  2 s.c o m
 * @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);
}

From source file:net.mindengine.galen.utils.GalenUtils.java

public static File makeFullScreenshot(WebDriver driver) throws IOException, InterruptedException {
    // scroll up first
    scrollVerticallyTo(driver, 0);/* w  ww.  ja va  2  s  . co  m*/
    byte[] bytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
    BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));
    int capturedWidth = image.getWidth();
    int capturedHeight = image.getHeight();

    long longScrollHeight = (Long) ((JavascriptExecutor) driver).executeScript(
            "return Math.max(" + "document.body.scrollHeight, document.documentElement.scrollHeight,"
                    + "document.body.offsetHeight, document.documentElement.offsetHeight,"
                    + "document.body.clientHeight, document.documentElement.clientHeight);");

    Double devicePixelRatio = ((Number) ((JavascriptExecutor) driver)
            .executeScript(JS_RETRIEVE_DEVICE_PIXEL_RATIO)).doubleValue();

    int scrollHeight = (int) longScrollHeight;

    File file = File.createTempFile("screenshot", ".png");

    int adaptedCapturedHeight = (int) (((double) capturedHeight) / devicePixelRatio);

    BufferedImage resultingImage;

    if (Math.abs(adaptedCapturedHeight - scrollHeight) > 40) {
        int scrollOffset = adaptedCapturedHeight;

        int times = scrollHeight / adaptedCapturedHeight;
        int leftover = scrollHeight % adaptedCapturedHeight;

        final BufferedImage tiledImage = new BufferedImage(capturedWidth,
                (int) (((double) scrollHeight) * devicePixelRatio), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2dTile = tiledImage.createGraphics();
        g2dTile.drawImage(image, 0, 0, null);

        int scroll = 0;
        for (int i = 0; i < times - 1; i++) {
            scroll += scrollOffset;
            scrollVerticallyTo(driver, scroll);
            BufferedImage nextImage = ImageIO.read(
                    new ByteArrayInputStream(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES)));
            g2dTile.drawImage(nextImage, 0, (i + 1) * capturedHeight, null);
        }
        if (leftover > 0) {
            scroll += scrollOffset;
            scrollVerticallyTo(driver, scroll);
            BufferedImage nextImage = ImageIO.read(
                    new ByteArrayInputStream(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES)));
            BufferedImage lastPart = nextImage.getSubimage(0,
                    nextImage.getHeight() - (int) (((double) leftover) * devicePixelRatio),
                    nextImage.getWidth(), leftover);
            g2dTile.drawImage(lastPart, 0, times * capturedHeight, null);
        }

        scrollVerticallyTo(driver, 0);

        resultingImage = tiledImage;
    } else {
        resultingImage = image;
    }

    if (GalenConfig.getConfig().shouldAutoresizeScreenshots()) {
        resultingImage = GalenUtils.resizeScreenshotIfNeeded(driver, resultingImage);
    }

    ImageIO.write(resultingImage, "png", file);
    return file;
}