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.github.zhanhb.ckfinder.connector.utils.ImageUtils.java

/**
 * Uploads image and if the image size is larger than maximum allowed it
 * resizes the image./*  w ww . j  a v a 2 s .  c  o m*/
 *
 * @param part servlet part
 * @param file file name
 * @param fileName name of file
 * @param context ckfinder context
 * @throws IOException when IO Exception occurs.
 */
public static void createTmpThumb(InputStreamSource part, Path file, String fileName, CKFinderContext context)
        throws IOException {
    BufferedImage image;
    try (InputStream stream = part.getInputStream()) {
        image = ImageIO.read(stream);
        if (image == null) {
            throw new IOException("Wrong file");
        }
    }
    ImageProperties imageProperties = context.getImage();
    Dimension dimension = createThumbDimension(image, imageProperties.getMaxWidth(),
            imageProperties.getMaxHeight());
    if (dimension.width == 0 || dimension.height == 0
            || (image.getHeight() <= dimension.height && image.getWidth() <= dimension.width)) {
        try (InputStream stream = part.getInputStream()) {
            Files.copy(stream, file, StandardCopyOption.REPLACE_EXISTING);
        }
    } else {
        resizeImage(image, dimension.width, dimension.height, imageProperties.getQuality(), file);
    }
    if (log.isTraceEnabled()) {
        log.trace("thumb size: {}", Files.size(file));
    }
}

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

/**
 * Rescales using predefined min,max intensities and converts to 8bit. Works for gray- and rgb color images.
 *
 * @param bi16/*from   ww w. j a va  2  s  .  co m*/
 * @return
 */
public static BufferedImage convertTo8bit(BufferedImage bi16, int min, int max) {
    BufferedImage bi = null;
    if (bi16.getSampleModel().getNumBands() == 1) {
        bi16 = ImageUtils.scaleIntensities(bi16, new int[] { min }, new int[] { max });
        bi = new BufferedImage(bi16.getWidth(), bi16.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
    } else if (bi16.getSampleModel().getNumBands() == 3) {
        throw new IllegalArgumentException("only grayscale images supported");
    } else {
        throw new IllegalArgumentException(
                "Only images with 1 band (gray-color) or 3 bands (rgb) supported. This image has "
                        + bi16.getSampleModel().getNumBands() + " bands.");
    }
    Graphics2D g2d = bi.createGraphics();
    g2d.drawImage(bi16, 0, 0, null);
    g2d.dispose();
    return bi;
}

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

/**
 * Extract magical image properties used by the getBlock function.
 * /*from  www.  ja va 2  s .c  o  m*/
 * @param image
 *            a BufferedImage
 * @return an ImageProperties descriptor object
 */
public static final ImageProperties getImageProperties(final BufferedImage image) {
    final int imageType = image.getType();
    ImageProperties p = new ImageProperties();
    p.image = image;
    p.raster = image.getRaster();
    p.alpha = imageType == TYPE_INT_ARGB || imageType == BufferedImage.TYPE_4BYTE_ABGR;
    boolean rgb = imageType == TYPE_INT_ARGB || imageType == TYPE_INT_RGB;
    boolean bgr = imageType == BufferedImage.TYPE_INT_BGR || imageType == BufferedImage.TYPE_3BYTE_BGR
            || imageType == BufferedImage.TYPE_4BYTE_ABGR;
    p.width = image.getWidth();
    p.height = image.getHeight();
    p.fallback = !(rgb || bgr);
    return p;
}

From source file:net.semanticmetadata.lire.utils.FileUtils.java

public static void saveImageResultsToPng(String prefix, TopDocs hits, String queryImage, IndexReader ir)
        throws IOException {
    LinkedList<BufferedImage> results = new LinkedList<BufferedImage>();
    int width = 0;
    for (int i = 0; i < Math.min(hits.scoreDocs.length, 10); i++) {
        // hits.score(i)
        // hits.doc(i).get("descriptorImageIdentifier")
        BufferedImage tmp = ImageIO
                .read(new FileInputStream(ir.document(hits.scoreDocs[i].doc).get("descriptorImageIdentifier")));
        if (tmp.getHeight() > 200) {
            double factor = 200d / ((double) tmp.getHeight());
            tmp = ImageUtils.scaleImage(tmp, (int) (tmp.getWidth() * factor), 200);
        }/* w  ww  . j  a va2 s .  c om*/
        width += tmp.getWidth() + 5;
        results.add(tmp);
    }
    BufferedImage result = new BufferedImage(width, 220, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = (Graphics2D) result.getGraphics();
    g2.setColor(Color.black);
    g2.clearRect(0, 0, result.getWidth(), result.getHeight());
    g2.setColor(Color.green);
    g2.setFont(Font.decode("\"Arial\", Font.BOLD, 12"));
    int offset = 0;
    int count = 0;
    for (Iterator<BufferedImage> iterator = results.iterator(); iterator.hasNext();) {
        BufferedImage next = iterator.next();
        g2.drawImage(next, offset, 20, null);
        g2.drawString(hits.scoreDocs[count].score + "", offset + 5, 12);
        offset += next.getWidth() + 5;
        count++;
    }
    ImageIO.write(result, "PNG", new File(prefix + "_" + (System.currentTimeMillis() / 1000) + ".png"));
}

From source file:FileUtils.java

/**
 * Convenience method that returns a scaled instance of the
 * provided {@code BufferedImage}.//from  w  w w. j a  va  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 = (BufferedImage) 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:view.FramePrincipal.java

private static BufferedImage createBufferedImage(String fileName) {
    BufferedImage image = null;
    try {//from w ww  . java  2 s .  com
        image = ImageIO.read(new File(fileName));
    } catch (IOException e) {
        return null;
    }

    int sizeX = image.getWidth();
    int sizeY = image.getHeight();

    BufferedImage result = new BufferedImage(sizeX, sizeY, BufferedImage.TYPE_INT_RGB);
    Graphics g = result.createGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();
    return result;
}

From source file:net.semanticmetadata.lire.utils.FileUtils.java

public static void saveImageResultsToPng(String prefix, ImageSearchHits hits, String queryImage,
        IndexReader reader) throws IOException {
    LinkedList<BufferedImage> results = new LinkedList<BufferedImage>();
    int width = 0;
    for (int i = 0; i < hits.length(); i++) {
        // hits.score(i)
        // hits.doc(i).get("descriptorImageIdentifier")
        BufferedImage tmp = ImageIO.read(new FileInputStream(
                reader.document(hits.documentID(i)).getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0]));
        //            if (tmp.getHeight() > 200) {
        double factor = 200d / ((double) tmp.getHeight());
        tmp = ImageUtils.scaleImage(tmp, (int) (tmp.getWidth() * factor), 200);
        //            }
        width += tmp.getWidth() + 5;// w w w  . ja  v  a 2  s. c  o  m
        results.add(tmp);
    }
    BufferedImage result = new BufferedImage(width, 220, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = (Graphics2D) result.getGraphics();
    g2.setColor(Color.white);
    g2.setBackground(Color.white);
    g2.clearRect(0, 0, result.getWidth(), result.getHeight());
    g2.setColor(Color.black);
    g2.setFont(Font.decode("\"Arial\", Font.BOLD, 12"));
    int offset = 0;
    int count = 0;
    for (Iterator<BufferedImage> iterator = results.iterator(); iterator.hasNext();) {
        BufferedImage next = iterator.next();
        g2.drawImage(next, offset, 20, null);
        g2.drawString(hits.score(count) + "", offset + 5, 12);
        offset += next.getWidth() + 5;
        count++;
    }
    ImageIO.write(result, "PNG", new File(prefix + "_" + (System.currentTimeMillis() / 1000) + ".png"));
}

From source file:com.android.hierarchyviewerlib.device.DeviceBridge.java

private static boolean readLayer(DataInputStream in, PsdFile psd) {
    try {//w  w  w.j av  a2  s  .  c  o  m
        if (in.read() == 2) {
            return false;
        }
        String name = in.readUTF();
        boolean visible = in.read() == 1;
        int x = in.readInt();
        int y = in.readInt();
        int dataSize = in.readInt();

        byte[] data = new byte[dataSize];
        int read = 0;
        while (read < dataSize) {
            read += in.read(data, read, dataSize - read);
        }

        ByteArrayInputStream arrayIn = new ByteArrayInputStream(data);
        BufferedImage chunk = ImageIO.read(arrayIn);

        // Ensure the image is in the right format
        BufferedImage image = new BufferedImage(chunk.getWidth(), chunk.getHeight(),
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();
        g.drawImage(chunk, null, 0, 0);
        g.dispose();

        psd.addLayer(name, image, new Point(x, y), visible);

        return true;
    } catch (Exception e) {
        return false;
    }
}

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

/**
 * ?// w  w w.  j  av a  2s  . co m
 *
 * @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:it.geosolutions.imageio.plugins.nitronitf.ImageIOUtils.java

public static JFrame showImage(BufferedImage image, String title, boolean fitToScreen) {
    JFrame frame = new JFrame(title != null ? title : "");
    frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

    Image im = image;/*  www .  jav  a 2  s  .  com*/

    if (fitToScreen) {
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        int imageHeight = image.getHeight();
        int imageWidth = image.getWidth();
        if (imageHeight > screen.height || imageWidth > screen.width) {
            double hRatio = (imageHeight - screen.height) / screen.height;
            double wRatio = (imageWidth - screen.width) / screen.width;

            int w = -1;
            int h = -1;

            if (hRatio > wRatio)
                h = screen.height;
            else
                w = screen.width;
            im = image.getScaledInstance(w, h, Image.SCALE_DEFAULT);
        }
    }

    JLabel label = new JLabel(new ImageIcon(im));
    frame.getContentPane().add(label, BorderLayout.CENTER);
    frame.pack();
    centerWindow(frame);
    frame.setVisible(true);
    return frame;
}