Example usage for java.awt.image BufferedImage getWidth

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

Introduction

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

Prototype

public int getWidth() 

Source Link

Document

Returns the width of the BufferedImage .

Usage

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);//w w  w . j  av  a 2  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:com.google.zxing.web.DecodeServlet.java

private static void processStream(InputStream is, ServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    BufferedImage image;
    try {//from   www  .  j  a  va2  s. c  o  m
        image = ImageIO.read(is);
    } catch (IOException | CMMException | IllegalArgumentException ioe) {
        log.info(ioe.toString());
        // Have seen these in some logs
        response.sendRedirect("badimage.jspx");
        return;
    }
    if (image == null) {
        response.sendRedirect("badimage.jspx");
        return;
    }
    if (image.getHeight() <= 1 || image.getWidth() <= 1 || image.getHeight() * image.getWidth() > MAX_PIXELS) {
        log.info("Dimensions out of bounds: " + image.getWidth() + 'x' + image.getHeight());
        response.sendRedirect("badimage.jspx");
        return;
    }

    processImage(image, request, response);
}

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 w  w  w .ja va 2  s . com
    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:it.reexon.lib.files.FileUtils.java

/**
 * Convenience method that returns a scaled instance of the provided {@code BufferedImage}. 
 *  /* ww  w.ja v  a  2s  .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.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   ww w  .  ja va2  s .c om
 * @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: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   ww w.j av a 2  s .  co  m
        }
    }

    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: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 ava2s  .co  m

    }
    return grayImage;
}

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

/**
 * Convenience method that returns a scaled instance of the provided {@link BufferedImage}.
 * //from  ww w  . j a  v a  2  s .  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 {/*  w  w w. j  a  va  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.uwsoft.editor.proxy.ResolutionManager.java

public static BufferedImage imageResize(File file, float ratio) {
    BufferedImage destinationBufferedImage = null;
    try {/*from   w ww .jav a 2 s.  co  m*/
        BufferedImage sourceBufferedImage = ImageIO.read(file);
        if (ratio == 1.0) {
            return sourceBufferedImage;
        }
        // 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;
}