Example usage for java.awt.image BufferedImage getHeight

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

Introduction

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

Prototype

public int getHeight() 

Source Link

Document

Returns the height of the BufferedImage .

Usage

From source file:com.shending.support.CompressPic.java

/**
 * ?/*from  w  ww .  j  a va  2s  .  c  om*/
 *
 * @param srcFile
 * @param dstFile
 * @param widthRange
 * @param heightRange
 */
public static void cutSquare(String srcFile, String dstFile, int widthRange, int heightRange, int width,
        int height) {
    int x = 0;
    int y = 0;
    try {
        ImageInputStream iis = ImageIO.createImageInputStream(new File(srcFile));
        Iterator<ImageReader> iterator = ImageIO.getImageReaders(iis);
        ImageReader reader = (ImageReader) iterator.next();
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
        int oldWidth = reader.getWidth(0);
        int oldHeight = reader.getHeight(0);
        int newWidth, newHeight;
        if (width <= oldWidth && height <= oldHeight) {
            newWidth = oldHeight * widthRange / heightRange;
            if (newWidth < oldWidth) {
                newHeight = oldHeight;
                x = (oldWidth - newWidth) / 2;
            } else {
                newWidth = oldWidth;
                newHeight = oldWidth * heightRange / widthRange;
                y = (oldHeight - newHeight) / 2;
            }
            Rectangle rectangle = new Rectangle(x, y, newWidth, newHeight);
            param.setSourceRegion(rectangle);
            BufferedImage bi = reader.read(0, param);
            BufferedImage tag = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(bi.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
            File file = new File(dstFile);
            ImageIO.write(tag, reader.getFormatName(), file);
        } else {
            BufferedImage bi = reader.read(0, param);
            BufferedImage tag = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = tag.createGraphics();
            g2d.setColor(Color.WHITE);
            g2d.fillRect(0, 0, tag.getWidth(), tag.getHeight());
            g2d.drawImage(bi.getScaledInstance(bi.getWidth(), bi.getHeight(), Image.SCALE_SMOOTH),
                    (width - bi.getWidth()) / 2, (height - bi.getHeight()) / 2, null);
            g2d.dispose();
            File file = new File(dstFile);
            ImageIO.write(tag, reader.getFormatName(), file);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.occamlab.te.parsers.ImageParser.java

private static String getBase64Data(BufferedImage buffImage, String formatName, Node node) throws Exception {
    int numBytes = buffImage.getWidth() * buffImage.getHeight() * 4;
    ByteArrayOutputStream baos = new ByteArrayOutputStream(numBytes);
    ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
    boolean status = ImageIO.write(buffImage, formatName, ios);
    if (!status) {
        throw new Exception("No suitable ImageIO writer found by ImageParser.getBase64Data() for image format "
                + formatName);//from   w w w. jav  a2 s  .c om
    }
    byte[] imageData = baos.toByteArray();
    // String base64String = Base64.encodeBase64String(imageData); this is
    // unchunked (no line breaks) which is unwieldy
    byte[] base64Data = Base64.encodeBase64Chunked(imageData);
    // 2011-11-15 PwD uncomment for Java 1.7 String base64String = new
    // String(base64Data, StandardCharsets.UTF_8);
    String base64String = new String(base64Data, "UTF-8"); // 2011-11-15 PwD
                                                           // for Java 1.6;
                                                           // remove for
                                                           // Java 1.7
    return base64String;
}

From source file:imageLines.ImageHelpers.java

public static BufferedImage getScaledInstance(BufferedImage img, int targetWidth, int targetHeight, Object hint,
        boolean higherQuality) {
    int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB
            : BufferedImage.TYPE_INT_ARGB;
    BufferedImage ret = (BufferedImage) img;
    int w, h;//from www.ja  va2s  .  c  o m
    if (higherQuality) {
        // 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();
    } else {
        // Use one-step technique: scale directly from original
        // size to target size with a single drawImage() call
        w = targetWidth;
        h = targetHeight;
    }

    do {
        if (higherQuality && w > targetWidth) {
            w /= 2;
            if (w < targetWidth) {
                w = targetWidth;
            }
        }

        if (higherQuality && h > targetHeight) {
            h /= 2;
            if (h < targetHeight) {
                h = targetHeight;
            }
        }

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

        ret = tmp;
    } while (w != targetWidth || h != targetHeight);

    return ret;
}

From source file:de._13ducks.cor.graphics.GraphicsComponent.java

public static BufferedImage grayScale(BufferedImage im) {
    // Verwandelt ein Bild ein eine Grayscale-Version, behlt aber die Transparenz
    BufferedImage grayImage = new BufferedImage(im.getWidth(), im.getHeight(), BufferedImage.TYPE_INT_ARGB);

    for (int x = 0; x < im.getWidth(); x++) {
        for (int y = 0; y < im.getHeight(); y++) {
            int argb = im.getRGB(x, y);
            int a = (argb >> 24) & 0xff;
            int r = (argb >> 16) & 0xff;
            int g = (argb >> 8) & 0xff;
            int b = (argb) & 0xff;
            int l = (int) (.299 * r + .587 * g + .114 * b); //luminance
            grayImage.setRGB(x, y, (a << 24) + (l << 16) + (l << 8) + l);
        }/*from w  w  w . j  a  v a 2s.  com*/

    }
    return grayImage;
}

From source file:it.reexon.lib.files.FileUtils.java

/**
 * Convenience method that returns a scaled instance of the provided {@code BufferedImage}. 
 *  /*from   w ww. j  a  v  a  2 s  . c o m*/
 * @param img the original image to be scaled 
 * @param targetWidth the desired width of the scaled instance, in pixels 
 * @param targetHeight the desired height of the scaled instance, in pixels 
 * @param hint one of the rendering hints that corresponds to {@code RenderingHints.KEY_INTERPOLATION} (e.g. 
 *        {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR}, {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR}, 
 *        {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC}) 
 * @param higherQuality if true, this method will use a multi-step scaling technique that provides higher quality than the 
 *        usual one-step technique (only useful in downscaling cases, where {@code targetWidth} or {@code targetHeight} is 
 *        smaller than the original dimensions, and generally only when the {@code BILINEAR} hint is specified) 
 * @return a scaled version of the original {@code BufferedImage} 
 */
public static BufferedImage getScaledInstance(BufferedImage img, int targetWidth, int targetHeight, Object hint,
        boolean higherQuality) {
    final int type = img.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB
            : BufferedImage.TYPE_INT_ARGB;
    BufferedImage ret = img;
    int w;
    int h;
    if (higherQuality) {
        // 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();
    } else {
        // Use one-step technique: scale directly from original 
        // size to target size with a single drawImage() call 
        w = targetWidth;
        h = targetHeight;
    }

    do {
        if (higherQuality && w > targetWidth) {
            w /= 2;
            if (w < targetWidth) {
                w = targetWidth;
            }
        }

        if (higherQuality && h > targetHeight) {
            h /= 2;
            if (h < targetHeight) {
                h = targetHeight;
            }
        }

        final BufferedImage tmp = new BufferedImage(w, h, type);
        final Graphics2D g2 = tmp.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
        g2.drawImage(ret, 0, 0, w, h, null);
        g2.dispose();

        ret = tmp;
    } while (w != targetWidth || h != targetHeight);

    return ret;
}

From source file:com.actelion.research.orbit.imageAnalysis.utils.ImageUtils.java

public static int[] getPercentileIntensity(BufferedImage image, double percentile) {
    WritableRaster raster = image.getRaster();
    int[] intensities = new int[raster.getNumBands()];

    DescriptiveStatistics[] ds = new DescriptiveStatistics[raster.getNumBands()];
    for (int i = 0; i < raster.getNumBands(); i++)
        ds[i] = new DescriptiveStatistics();

    int width = image.getWidth();
    int height = image.getHeight();

    for (int row = 0; row < height; row++) {
        for (int col = 0; col < width; col++) {
            for (int band = 0; band < raster.getNumBands(); band++) {
                ds[band].addValue(raster.getSample(col, row, band));
            }/*from  w w  w.j a  v  a 2  s  .c  om*/
        }
    }

    for (int i = 0; i < ds.length; i++) {
        if (percentile == 0d)
            intensities[i] = (int) ds[i].getMin();
        else if (percentile == 100d)
            intensities[i] = (int) ds[i].getMax();
        else
            intensities[i] = (int) ds[i].getPercentile(percentile);
    }
    return intensities;
}

From source file:com.piaoyou.util.ImageUtil.java

/**
 * @todo: xem lai ham nay, neu kich thuoc nho hon max thi ta luu truc tiep
 *          inputStream xuong thumbnailFile luon
 *
 * This method create a thumbnail and reserve the ratio of the output image
 * NOTE: This method closes the inputStream after it have done its work.
 *
 * @param inputStream     the stream of a jpeg file
 * @param outputStream    the output stream
 * @param maxWidth        the maximum width of the image
 * @param maxHeight       the maximum height of the image
 * @throws IOException//from w w  w .  j  a  v a 2  s. c o m
 * @throws BadInputException
 */
public static void createThumbnail(InputStream inputStream, OutputStream outputStream, int maxWidth,
        int maxHeight) throws IOException {

    if (inputStream == null) {
        throw new IllegalArgumentException("inputStream must not be null.");
    }
    if (outputStream == null) {
        throw new IllegalArgumentException("outputStream must not be null.");
    }

    //boolean useSun = false;
    if (maxWidth <= 0) {
        throw new IllegalArgumentException("maxWidth must >= 0");
    }
    if (maxHeight <= 0) {
        throw new IllegalArgumentException("maxHeight must >= 0");
    }

    try {
        //JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(inputStream);
        //BufferedImage srcImage = decoder.decodeAsBufferedImage();
        byte[] srcByte = FileUtil.getBytes(inputStream);
        InputStream is = new ByteArrayInputStream(srcByte);
        //ImageIcon imageIcon = new ImageIcon(srcByte);
        //Image srcImage = imageIcon.getImage();

        BufferedImage srcImage = ImageIO.read(is);
        if (srcImage == null) {
            throw new IOException("Cannot decode image. Please check your file again.");
        }

        int imgWidth = srcImage.getWidth();
        int imgHeight = srcImage.getHeight();
        //          imgWidth or imgHeight could be -1, which is considered as an assertion
        AssertionUtil.doAssert((imgWidth > 0) && (imgHeight > 0),
                "Assertion: ImageUtil: cannot get the image size.");
        // Set the scale.
        AffineTransform tx = new AffineTransform();
        if ((imgWidth > maxWidth) || (imgHeight > maxHeight)) {
            double scaleX = (double) maxWidth / imgWidth;
            double scaleY = (double) maxHeight / imgHeight;
            double scaleRatio = (scaleX < scaleY) ? scaleX : scaleY;
            imgWidth = (int) (imgWidth * scaleX);
            imgWidth = (imgWidth == 0) ? 1 : imgWidth;
            imgHeight = (int) (imgHeight * scaleY);
            imgHeight = (imgHeight == 0) ? 1 : imgHeight;
            // scale as needed
            tx.scale(scaleRatio, scaleRatio);
        } else {// we don't need any transform here, just save it to file and return
            outputStream.write(srcByte);
            return;
        }

        // create thumbnail image
        BufferedImage bufferedImage = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);

        Graphics2D g = bufferedImage.createGraphics();
        boolean useTransform = false;
        if (useTransform) {// use transfrom to draw
            //log.trace("use transform");
            g.drawImage(srcImage, tx, null);
        } else {// use java filter
            //log.trace("use filter");
            Image scaleImage = getScaledInstance(srcImage, imgWidth, imgHeight);
            g.drawImage(scaleImage, 0, 0, null);
        }
        g.dispose();// free resource
        // write it to outputStream 
        // JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream);
        // encoder.encode(bufferedImage);

        ImageIO.write(bufferedImage, "jpeg", outputStream);
    } catch (IOException e) {
        log.error("Error", e);
        throw e;
    } finally {// this finally is very important
        try {
            inputStream.close();
        } catch (IOException e) {
            /* ignore */
            e.printStackTrace();
        }
        try {
            outputStream.close();
        } catch (IOException e) {/* ignore */
            e.printStackTrace();
        }
    }
}

From source file:de.mpg.imeji.logic.storage.util.ImageUtils.java

/**
 * Convenience method that returns a scaled instance of the provided {@link BufferedImage}.
 * /*from  www .  j  av a  2s.  com*/
 * @param img the original image to be scaled
 * @param targetWidth the desired width of the scaled instance, in pixels
 * @param targetHeight the desired height of the scaled instance, in pixels
 * @param hint one of the rendering hints that corresponds to {@code RenderingHints.KEY_INTERPOLATION} (e.g.
 *            {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR},
 *            {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR},
 *            {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC})
 * @param higherQuality if true, this method will use a multi-step scaling technique that provides higher quality
 *            than the usual one-step technique (only useful in downscaling cases, where {@code targetWidth} or
 *            {@code targetHeight} is smaller than the original dimensions, and generally only when the
 *            {@code BILINEAR} hint is specified)
 * @return a scaled version of the original {@link BufferedImage}
 */
public static BufferedImage getScaledInstance(BufferedImage img, int targetWidth, int targetHeight, Object hint,
        boolean higherQuality) {
    int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB
            : BufferedImage.TYPE_INT_ARGB;
    BufferedImage ret = img;
    int w, h;
    if (higherQuality) {
        // 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();
    } else {
        // Use one-step technique: scale directly from original
        // size to target size with a single drawImage() call
        w = targetWidth;
        h = targetHeight;
    }
    do {
        if (higherQuality && w > targetWidth) {
            w /= 2;
            if (w < targetWidth) {
                w = targetWidth;
            }
        }
        if (higherQuality && h > targetHeight) {
            h /= 2;
            if (h < targetHeight) {
                h = targetHeight;
            }
        }
        BufferedImage tmp = new BufferedImage(w, h, type);
        Graphics2D g2 = tmp.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
        g2.drawImage(ret, 0, 0, w, h, null);
        g2.dispose();
        ret = tmp;
    } while (w != targetWidth || h != targetHeight);
    return ret;
}

From source file:com.o2d.pkayjava.editor.proxy.ResolutionManager.java

public static BufferedImage imageResize(File file, float ratio) {
    BufferedImage destinationBufferedImage = null;
    try {//from   ww  w .  j  a v a 2s  .  c o  m
        BufferedImage sourceBufferedImage = ImageIO.read(file);
        if (ratio == 1.0) {
            return null;
        }
        // When image has to be resized smaller then 3 pixels we should leave it as is, as to ResampleOP limitations
        // But it should also trigger a warning dialog at the and of the import, to notify the user of non resized images.
        if (sourceBufferedImage.getWidth() * ratio < 3 || sourceBufferedImage.getHeight() * ratio < 3) {
            return null;
        }
        int newWidth = Math.max(3, Math.round(sourceBufferedImage.getWidth() * ratio));
        int newHeight = Math.max(3, Math.round(sourceBufferedImage.getHeight() * ratio));
        String name = file.getName();
        Integer[] patches = null;
        if (name.endsWith(EXTENSION_9PATCH)) {
            patches = NinePatchUtils.findPatches(sourceBufferedImage);
            sourceBufferedImage = NinePatchUtils.removePatches(sourceBufferedImage);

            newWidth = Math.round(sourceBufferedImage.getWidth() * ratio);
            newHeight = Math.round(sourceBufferedImage.getHeight() * ratio);
            System.out.println(sourceBufferedImage.getWidth());

            destinationBufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2 = destinationBufferedImage.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
            g2.drawImage(sourceBufferedImage, 0, 0, newWidth, newHeight, null);
            g2.dispose();

        } else {
            // resize with bilinear filter
            ResampleOp resampleOp = new ResampleOp(newWidth, newHeight);
            destinationBufferedImage = resampleOp.filter(sourceBufferedImage, null);
        }

        if (patches != null) {
            destinationBufferedImage = NinePatchUtils.convertTo9Patch(destinationBufferedImage, patches, ratio);
        }

    } catch (IOException ignored) {

    }

    return destinationBufferedImage;
}

From source file:com.actelion.research.orbit.imageAnalysis.utils.ImageUtils.java

/**
 * scales bands to min = 0 & max = 2^8 or 2^16
 *
 * @param image/*w  w w  . ja v a2  s  .  c  om*/
 * @param min   int[] containing minima per band
 * @param max
 * @return
 */
public static BufferedImage scaleIntensities(BufferedImage image, int[] min, int[] max)
        throws IllegalArgumentException {
    WritableRaster raster = image.getRaster();

    if ((min.length != max.length) || min.length != raster.getNumBands())
        throw new IllegalArgumentException(
                "Please ensure consistency of min and max arrays and number of bands in image");

    int width = image.getWidth();
    int height = image.getHeight();

    for (int row = 0; row < height; row++) {
        for (int col = 0; col < width; col++) {
            for (int band = 0; band < raster.getNumBands(); band++) {
                int pixel = raster.getSample(col, row, band);
                if (pixel < min[band])
                    pixel = min[band];
                if (pixel > max[band])
                    pixel = max[band];
                pixel = ((int) (((((double) pixel - min[band]) / (max[band] - min[band]))
                        * ((int) Math.pow(2, image.getColorModel().getPixelSize()) - 1)) + 0.5));
                raster.setSample(col, row, band, pixel);
            }
        }
    }

    return image;
}