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:org.hippoecm.frontend.plugins.gallery.imageutil.ImageUtils.java

public static BufferedImage scaleImage(BufferedImage img, int xOffset, int yOffset, int sourceWidth,
        int sourceHeight, int targetWidth, int targetHeight, Object hint, boolean highQuality) {

    if (sourceWidth <= 0 || sourceHeight <= 0 || targetWidth <= 0 || targetHeight <= 0) {
        return null;
    }/*from w  ww.  j  ava 2 s.com*/

    int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB
            : BufferedImage.TYPE_INT_ARGB;

    BufferedImage result = img;
    if (xOffset != 0 || yOffset != 0 || sourceWidth != img.getWidth() || sourceHeight != img.getHeight()) {
        result = result.getSubimage(xOffset, yOffset, sourceWidth, sourceHeight);
    }

    int width, height;

    if (highQuality) {
        // Use the multiple step technique: start with original size, then scale down in multiple passes with
        // drawImage() until the target size is reached
        width = img.getWidth();
        height = img.getHeight();
    } else {
        // Use one-step technique: scale directly from original size to target size with a single drawImage() call
        width = targetWidth;
        height = targetHeight;
    }

    do {
        if (highQuality && width > targetWidth) {
            width /= 2;
        }
        width = Math.max(width, targetWidth);

        if (highQuality && height > targetHeight) {
            height /= 2;
        }
        height = Math.max(height, targetHeight);

        BufferedImage tmp = new BufferedImage(width, height, type);

        Graphics2D g2 = tmp.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
        g2.drawImage(result, 0, 0, width, height, null);
        g2.dispose();

        result = tmp;
    } while (width != targetWidth || height != targetHeight);

    return result;
}

From source file:org.madsonic.controller.CoverArtController.java

public static BufferedImage scale(BufferedImage image, int width, int height) {

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

    // For optimal results, use step by step bilinear resampling - halfing the size at each step.
    do {/*from ww w  .j a v a 2s.c o m*/
        w /= 2;
        h /= 2;
        if (w < width) {
            w = width;
        }
        if (h < height) {
            h = height;
        }

        double thumbRatio = (double) width / (double) height;
        double aspectRatio = (double) w / (double) h;

        //            LOG.debug("## thumbsRatio: " + thumbRatio);
        //            LOG.debug("## aspectRatio: " + aspectRatio);

        if (thumbRatio < aspectRatio) {
            h = (int) (w / aspectRatio);
        } else {
            w = (int) (h * aspectRatio);
        }

        BufferedImage temp = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = temp.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(thumb, 0, 0, w, h, null);
        g2.dispose();

        thumb = temp;
    } while (w != width);

    //FIXME: check
    if (thumb.getHeight() > thumb.getWidth()) {
        thumb = thumb.getSubimage(0, 0, thumb.getWidth(), thumb.getWidth());
    }
    return thumb;
}

From source file:org.medici.bia.service.peoplebase.PeopleBaseServiceImpl.java

/**
 * {@inheritDoc}/*w  ww . j  a v a 2 s  .  c  o m*/
 */
@Override
public void cropPortraitPerson(Integer personId, Double x, Double y, Double x2, Double y2, Double width,
        Double height) throws ApplicationThrowable {
    try {
        People person = getPeopleDAO().find(personId);

        if ((person != null) && (person.getPortrait())) {
            String portraitPath = ApplicationPropertyManager.getApplicationProperty("portrait.person.path");
            File portraitFile = new File(portraitPath + "/" + person.getPortraitImageName());
            BufferedImage bufferedImage = ImageIO.read(portraitFile);
            //here code for cropping... TO BE TESTED...
            BufferedImage croppedBufferedImage = bufferedImage.getSubimage(x.intValue(), y.intValue(),
                    width.intValue(), height.intValue());
            ImageIO.write(croppedBufferedImage, "jpg", portraitFile);
        }
    } catch (Throwable th) {
        throw new ApplicationThrowable(th);
    }

}

From source file:org.medici.bia.service.user.UserServiceImpl.java

/**
 * {@inheritDoc}/*  w  w  w.  ja v a  2s . c o  m*/
 */
@Override
public void cropPortraitUser(String account, Double x, Double y, Double x2, Double y2, Double width,
        Double height) throws ApplicationThrowable {
    try {
        User user = getUserDAO().findUser(account);

        if ((user != null) && (user.getPortrait())) {
            String portraitPath = ApplicationPropertyManager.getApplicationProperty("portrait.user.path");
            File portraitFile = new File(portraitPath + "/" + user.getPortraitImageName());
            BufferedImage bufferedImage = ImageIO.read(portraitFile);
            //here code for cropping... TO BE TESTED...
            BufferedImage croppedBufferedImage = bufferedImage.getSubimage(x.intValue(), y.intValue(),
                    width.intValue(), height.intValue());
            ImageIO.write(croppedBufferedImage, "jpg", portraitFile);
        }
    } catch (Throwable th) {
        throw new ApplicationThrowable(th);
    }

}

From source file:org.olat.core.commons.services.image.spi.ImageHelperImpl.java

private static BufferedImage cropTo(BufferedImage img, Size size, Crop cropSelection) {
    int w = cropSelection.getWidth();
    int h = cropSelection.getHeight();
    int x = cropSelection.getX();
    int y = cropSelection.getY();
    //make sure that the sub image is in the raster (if not boum!!)
    w = Math.min(w, size.getWidth() - x);
    h = Math.min(h, size.getHeight() - y);
    //crop the image to see only the center of the image
    return img.getSubimage(x, y, w, h);
}

From source file:org.olat.core.commons.services.image.spi.ImageHelperImpl.java

/**
 * This code is very inspired on Chris Campbells article "The Perils of Image.getScaledInstance()"
 *
 * The article can be found here:/*ww  w.j a v  a 2  s . co  m*/
 * http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html
 *
 * Note that the filter method is threadsafe
 */
private static BufferedImage scaleFastTo(BufferedImage img, Size scaledSize) {
    if (!scaledSize.isChanged())
        return img;

    BufferedImage dest;
    if (img.getType() == BufferedImage.TYPE_CUSTOM) {
        dest = new BufferedImage(scaledSize.getWidth(), scaledSize.getHeight(), BufferedImage.TYPE_INT_ARGB);
    } else {
        dest = new BufferedImage(scaledSize.getWidth(), scaledSize.getHeight(), img.getType());
    }

    int dstWidth = scaledSize.getWidth();
    int dstHeight = scaledSize.getHeight();

    BufferedImage ret = img;
    int w, h;

    // Use multi-step technique: start with original size, then
    // scale down in multiple passes with drawImage()
    // until the target size is reached
    w = img.getWidth();
    h = img.getHeight();

    int x = scaledSize.getXOffset();
    int y = scaledSize.getYOffset();

    //crop the image to see only the center of the image
    if (x > 0 || y > 0) {
        ret = img.getSubimage(x, y, w - (2 * x), h - (2 * y));
    }

    do {
        if (w > dstWidth) {
            if (x > 0) {
                x /= 2;
            }
            w /= 2;
            if (w < dstWidth) {
                w = dstWidth;
            }
        } else {
            w = dstWidth;
        }

        if (h > dstHeight) {
            h /= 2;
            if (h < dstHeight) {
                h = dstHeight;
            }
        } else {
            h = dstHeight;
        }

        BufferedImage tmp;
        if (dest.getWidth() == w && dest.getHeight() == h && w == dstWidth && h == dstHeight) {
            tmp = dest;
        } else {
            tmp = new BufferedImage(w, h, dest.getType());
        }

        Graphics2D g2 = tmp.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(ret, 0, 0, w, h, null);
        g2.dispose();

        ret = tmp;
    } while (w != dstWidth || h != dstHeight);

    return ret;
}

From source file:org.primefaces.component.imagecropper.ImageCropperRenderer.java

@Override
public Object getConvertedValue(FacesContext context, UIComponent component, Object submittedValue)
        throws ConverterException {
    String coords = (String) submittedValue;

    if (isValueBlank(coords)) {
        return null;
    }/*from   w  w  w .  j a va 2s  .c o  m*/

    String[] cropCoords = coords.split("_");

    int x = (int) Double.parseDouble(cropCoords[0]);
    int y = (int) Double.parseDouble(cropCoords[1]);
    int w = (int) Double.parseDouble(cropCoords[2]);
    int h = (int) Double.parseDouble(cropCoords[3]);

    if (w <= 0 || h <= 0) {
        return null;
    }

    ImageCropper cropper = (ImageCropper) component;
    Resource resource = getImageResource(context, cropper);
    InputStream inputStream = null;
    String imagePath = cropper.getImage();
    String contentType = null;

    try {

        if (resource != null && !"RES_NOT_FOUND".equals(resource.toString())) {
            inputStream = resource.getInputStream();
            contentType = resource.getContentType();
        } else {

            boolean isExternal = imagePath.startsWith("http");

            if (isExternal) {
                URL url = new URL(imagePath);
                URLConnection urlConnection = url.openConnection();
                inputStream = urlConnection.getInputStream();
                contentType = urlConnection.getContentType();
            } else {
                ExternalContext externalContext = context.getExternalContext();
                File file = new File(externalContext.getRealPath("") + imagePath);
                inputStream = new FileInputStream(file);
            }
        }

        // wrap input stream by BoundedInputStream to prevent uncontrolled resource consumption (#3286)
        if (cropper.getSizeLimit() != null) {
            inputStream = new BoundedInputStream(inputStream, cropper.getSizeLimit());
        }

        BufferedImage outputImage = ImageIO.read(inputStream);

        // avoid java.awt.image.RasterFormatException: (x + width) is outside of Raster
        // see #1208
        if (x + w > outputImage.getWidth()) {
            w = outputImage.getWidth() - x;
        }
        if (y + h > outputImage.getHeight()) {
            h = outputImage.getHeight() - y;
        }

        BufferedImage cropped = outputImage.getSubimage(x, y, w, h);
        ByteArrayOutputStream croppedOutImage = new ByteArrayOutputStream();
        String format = guessImageFormat(contentType, imagePath);
        ImageIO.write(cropped, format, croppedOutImage);

        return new CroppedImage(cropper.getImage(), croppedOutImage.toByteArray(), x, y, w, h);
    } catch (IOException e) {
        throw new ConverterException(e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                LOGGER.severe(e.getMessage());
            }
        }
    }
}

From source file:org.safs.selenium.webdriver.lib.WDLibrary.java

/**
 * Capture the image on browser according to the rectangle relative to the browser.
 * @param rectangle Rectangle, within which to capture the image.
 * @return BufferedImage, the image within the rectangle on a browser, or the whole browser if rectangle is null.
 * @throws SeleniumPlusException/* www  .j  a va 2s  .  co  m*/
 */
public static BufferedImage captureBrowserArea(Rectangle rectangle) throws SeleniumPlusException {
    String debugmsg = StringUtils.debugmsg(false);
    try {
        //Get the whole page image
        byte[] imageBytes = ((TakesScreenshot) lastUsedWD).getScreenshotAs(OutputType.BYTES);
        BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));
        //img = new PngImage().read(new ByteArrayInputStream(imageBytes), true);
        //Get sub image according to the rectangle
        if (rectangle == null)
            return img;
        else {
            IndependantLog.debug(debugmsg + " the initial subarea is " + rectangle);
            //If the rectangle is beyond the browser, throw exception
            if (rectangle.x >= img.getWidth() || rectangle.y >= img.getHeight()) {
                throw new SeleniumPlusException("The component is totally outside of browser!");
            }
            if (rectangle.x < 0) {
                IndependantLog.debug(debugmsg + " subarea x coordinate should NOT be negative, set it to 0.");
                rectangle.x = 0;
            }
            if (rectangle.y < 0) {
                IndependantLog.debug(debugmsg + " subarea y coordinate should NOT be negative, set it to 0.");
                rectangle.y = 0;
            }

            //if the rectangle is larger than the captured browser image, then
            //we need to reduce the rectangle
            int tempW = rectangle.x + rectangle.width;
            int tempH = rectangle.y + rectangle.height;
            if (tempW > img.getWidth())
                rectangle.width = img.getWidth() - rectangle.x;
            if (tempH > img.getHeight())
                rectangle.height = img.getHeight() - rectangle.y;

            if (tempW > img.getWidth() || tempH > img.getHeight()) {
                IndependantLog.debug(debugmsg + " subarea has been adjusted to " + rectangle);
            }
            return img.getSubimage(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
        }
    } catch (Exception e) {
        String message = (rectangle == null ? "of whole browser" : "on browser area '" + rectangle + "'");
        message = "Failed to capture screenshot " + message;
        message += " due to " + e.getMessage();
        IndependantLog.error(debugmsg + message);
        throw new SeleniumPlusException(message);
    }
}

From source file:org.sbs.util.ImageCompress.java

/**
 * ?//from   ww  w. ja v  a 2  s  . c  om
 * 
 * @param image
 *            ??
 * @param subImageBounds
 *            ???
 * @param subImageFile
 *            ??
 * @throws IOException
 */
private 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);
}

From source file:org.silverpeas.core.io.media.image.thumbnail.control.ThumbnailController.java

protected static void createCropThumbnailFileOnServer(String pathOriginalFile, String pathCropdir,
        String pathCropFile, ThumbnailDetail thumbnail, int thumbnailWidth, int thumbnailHeight) {
    try {/* w  w w  . ja  va2 s .c  om*/
        // 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()) {
            Files.createFile(cropFile.toPath());
        }

        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) {
        SilverLogger.getLogger(ThumbnailController.class).warn(e);
    }
}