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:alfio.manager.UploadedResourceManager.java

private static Map<String, String> getAttributes(UploadBase64FileModification file) {
    if (!StringUtils.startsWith(file.getType(), "image/")) {
        return file.getAttributes();
    }/*from w ww .  j  a  v a2s .c  o m*/

    try {
        BufferedImage image = ImageIO.read(new ByteArrayInputStream(file.getFile()));
        Map<String, String> attributes = new HashMap<>(file.getAttributes());
        attributes.put(ATTR_IMG_WIDTH, String.valueOf(image.getWidth()));
        attributes.put(ATTR_IMG_HEIGHT, String.valueOf(image.getHeight()));
        return attributes;
    } catch (IOException e) {
        log.error("error while processing image: ", e);
        return file.getAttributes();
    }
}

From source file:ar.com.zauber.common.image.impl.AbstractImage.java

/**
 * Creates a thumbnail//  ww  w  . j a va 2  s .c o  m
 * 
 * @param is data source
 * @param os data source
 * @throws IOException if there is a problem reading is
 */
public static void createThumbnail(final InputStream is, final OutputStream os, final int target)
        throws IOException {
    final float compression = 0.85F;
    ImageWriter writer = null;
    MemoryCacheImageOutputStream mos = null;
    Graphics2D graphics2D = null;
    try {
        final BufferedImage bi = ImageIO.read(is);
        final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("JPG");
        if (!iter.hasNext()) {
            throw new IllegalStateException("can't find JPG subsystem");
        }

        int w = bi.getWidth(), h = bi.getHeight();
        if (w < target && h < target) {
            // nothing to recalculate, ya es chiquita.
        } else {
            if (w > h) {
                h = target * bi.getHeight() / bi.getWidth();
                w = target;
            } else {
                w = target * bi.getWidth() / bi.getHeight();
                h = target;
            }
        }
        // draw original image to thumbnail image object and
        // scale it to the new size on-the-fly
        final BufferedImage thumbImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        graphics2D = thumbImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(bi, 0, 0, w, h, null);

        writer = (ImageWriter) iter.next();
        final ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwp.setCompressionQuality(compression);
        mos = new MemoryCacheImageOutputStream(os);
        writer.setOutput(mos);
        writer.write(null, new IIOImage(thumbImage, null, null), iwp);
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (mos != null) {
            mos.close();
        }
        if (graphics2D != null) {
            graphics2D.dispose();
        }
        is.close();
        os.close();
    }
}

From source file:com.oneis.utils.ImageColouring.java

/**
 * Transform the colours in an image.//from w w w. j a va  2s.c o m
 *
 * @param Filename Full pathname to the source file
 * @param Method Which colouring method to use, use METHOD_* constants
 * @param Colours Array of 0xRRGGBB colours for recolouring
 * @param JPEGQuality If the image is a JPEG, the output quality for
 * reencoding
 * @param Output An OutputStream to write the file. Will be closed.
 */
static public void colourImage(String Filename, int Method, int[] Colours, int JPEGQuality, OutputStream Output)
        throws IOException {
    ColouringInfo colouringInfo = prepareForColouring(Method, Colours);

    String extension = Filename.substring(Filename.lastIndexOf('.') + 1, Filename.length());
    String outputFormat = extension;

    if (outputFormat.equals("gif")) {
        if (!colourImageGIF(Filename, colouringInfo, Output)) {
            throw new RuntimeException("Failed to directly colour GIF file");
        }
        return;
    }

    BufferedImage image = ImageIO.read(new File(Filename));
    int width = image.getWidth();
    int height = image.getHeight();

    // Rewrite the pixels
    int[] pixelBuffer = new int[width];
    for (int y = 0; y < height; ++y) {
        image.getRGB(0, y, width, 1, pixelBuffer, 0, width);
        doColouring(pixelBuffer, colouringInfo);
        image.setRGB(0, y, width, 1, pixelBuffer, 0, width);
    }

    // Writing is done the hard way to enable the JPEG quality to be set.
    // Get a writer
    Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(outputFormat);
    if (!iter.hasNext()) {
        throw new RuntimeException("Couldn't write image of type " + outputFormat);
    }

    ImageWriter writer = iter.next();

    ImageWriteParam iwparam = null;

    // Is it JPEG? If so, might want to set the quality
    if (outputFormat.equals("jpeg") || outputFormat.equals("jpg")) {
        // Clamp value
        int q = JPEGQuality;
        if (q < 10) {
            q = 10;
        }
        if (q > 100) {
            q = 100;
        }

        JPEGImageWriteParam jparam = new JPEGImageWriteParam(null);
        jparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        jparam.setCompressionQuality((float) (((float) q) / 100.0));
        iwparam = jparam;
    }

    ImageOutputStream output = ImageIO.createImageOutputStream(Output);
    writer.setOutput(output);
    writer.write(null, new IIOImage(image, null, null), iwparam);

    output.close();
}

From source file:net.sf.mcf2pdf.mcfelements.util.ImageUtil.java

public static BufferedImage readImage(File imageFile) throws IOException {
    int rotation = getImageRotation(imageFile);
    BufferedImage img = ImageIO.read(imageFile);

    if (rotation == 0) {
        return img;
    }/*  ww w.  j a v  a  2  s . c o m*/

    boolean swapXY = rotation != 180;

    BufferedImage rotated = new BufferedImage(swapXY ? img.getHeight() : img.getWidth(),
            swapXY ? img.getWidth() : img.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = rotated.createGraphics();
    g2d.translate((rotated.getWidth() - img.getWidth()) / 2, (rotated.getHeight() - img.getHeight()) / 2);
    g2d.rotate(Math.toRadians(rotation), img.getWidth() / 2, img.getHeight() / 2);

    g2d.drawImage(img, 0, 0, null);
    g2d.dispose();

    return rotated;
}

From source file:de.mprengemann.intellij.plugin.androidicons.images.ImageUtils.java

private static BufferedImage trim9PBorder(BufferedImage inputImage) {
    BufferedImage trimedImage = UIUtil.createImage(inputImage.getWidth() - 2, inputImage.getHeight() - 2,
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = trimedImage.createGraphics();
    g.drawImage(inputImage, 0, 0, trimedImage.getWidth(), trimedImage.getHeight(), 1, 1,
            inputImage.getWidth() - 1, inputImage.getHeight() - 1, null);
    g.dispose();//from w  w  w.  j  ava 2  s.  c om
    return trimedImage;
}

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

public static String[] getWidthAndHeightByWidth(InputStream image, int widthParam) {
    String[] result = new String[2];
    try {/*from  w w w  .  j  a v a 2  s . com*/
        BufferedImage inputBuf = ImageIO.read(image);
        // calcul de la taille de la sortie
        double inputBufWidth;
        double inputBufHeight;
        double width;
        double ratio;
        double height;
        if (inputBuf.getWidth() > widthParam) {
            inputBufWidth = inputBuf.getWidth();
            inputBufHeight = inputBuf.getHeight();
            width = widthParam;
            ratio = inputBufWidth / width;
            height = inputBufHeight / ratio;
        } else {
            width = inputBuf.getWidth();
            height = inputBuf.getHeight();
        }
        String sWidth = Double.toString(width);
        String sHeight = Double.toString(height);

        result[0] = sWidth.substring(0, sWidth.indexOf('.'));
        result[1] = sHeight.substring(0, sHeight.indexOf('.'));

        return result;
    } catch (Exception e) {
        if (image != null) {
            SilverTrace.error("util", "ImageUtil.getWidthAndHeightByWidth", "root.MSG_GEN_ERROR", e);
        }
    }
    result[0] = "";
    result[1] = "";
    return result;
}

From source file:com.esofthead.mycollab.mobile.ui.MobileAttachmentUtils.java

public static void saveContentsToRepo(String attachmentPath, Map<String, File> fileStores) {
    if (MapUtils.isNotEmpty(fileStores)) {
        ResourceService resourceService = ApplicationContextUtil.getSpringBean(ResourceService.class);
        for (String fileName : fileStores.keySet()) {
            try {
                String fileExt = "";
                int index = fileName.lastIndexOf(".");
                if (index > 0) {
                    fileExt = fileName.substring(index + 1, fileName.length());
                }/* w  w  w .  j  a  v  a 2 s  .c om*/

                if ("jpg".equalsIgnoreCase(fileExt) || "png".equalsIgnoreCase(fileExt)) {
                    try {
                        BufferedImage bufferedImage = ImageIO.read(fileStores.get(fileName));

                        int imgHeight = bufferedImage.getHeight();
                        int imgWidth = bufferedImage.getWidth();

                        BufferedImage scaledImage = null;

                        float scale;
                        float destWidth = 974;
                        float destHeight = 718;

                        float scaleX = Math.min(destHeight / imgHeight, 1);
                        float scaleY = Math.min(destWidth / imgWidth, 1);
                        scale = Math.min(scaleX, scaleY);
                        scaledImage = ImageUtil.scaleImage(bufferedImage, scale);

                        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                        ImageIO.write(scaledImage, fileExt, outStream);

                        resourceService.saveContent(constructContent(fileName, attachmentPath),
                                AppContext.getUsername(), new ByteArrayInputStream(outStream.toByteArray()),
                                AppContext.getAccountId());
                    } catch (IOException e) {
                        LOG.error("Error in upload file", e);
                        resourceService.saveContent(constructContent(fileName, attachmentPath),
                                AppContext.getUsername(), new FileInputStream(fileStores.get(fileName)),
                                AppContext.getAccountId());
                    }
                } else {
                    resourceService.saveContent(constructContent(fileName, attachmentPath),
                            AppContext.getUsername(), new FileInputStream(fileStores.get(fileName)),
                            AppContext.getAccountId());
                }

            } catch (FileNotFoundException e) {
                LOG.error("Error when attach content in UI", e);
            }
        }
    }
}

From source file:com.lingxiang2014.util.ImageUtils.java

public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) {
    Assert.notNull(srcFile);/*w w  w . java  2  s  .com*/
    Assert.notNull(destFile);
    Assert.state(destWidth > 0);
    Assert.state(destHeight > 0);
    if (type == Type.jdk) {
        Graphics2D graphics2D = null;
        ImageOutputStream imageOutputStream = null;
        ImageWriter imageWriter = null;
        try {
            BufferedImage srcBufferedImage = ImageIO.read(srcFile);
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            int width = destWidth;
            int height = destHeight;
            if (srcHeight >= srcWidth) {
                width = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth));
            } else {
                height = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight));
            }
            BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight,
                    BufferedImage.TYPE_INT_RGB);
            graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(BACKGROUND_COLOR);
            graphics2D.clearRect(0, 0, destWidth, destHeight);
            graphics2D.drawImage(srcBufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
                    (destWidth / 2) - (width / 2), (destHeight / 2) - (height / 2), null);

            imageOutputStream = ImageIO.createImageOutputStream(destFile);
            imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName()))
                    .next();
            imageWriter.setOutput(imageOutputStream);
            ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
            imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            imageWriteParam.setCompressionQuality((float) (DEST_QUALITY / 100.0));
            imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
            imageOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (graphics2D != null) {
                graphics2D.dispose();
            }
            if (imageWriter != null) {
                imageWriter.dispose();
            }
            if (imageOutputStream != null) {
                try {
                    imageOutputStream.close();
                } catch (IOException e) {
                }
            }
        }
    } else {
        IMOperation operation = new IMOperation();
        operation.thumbnail(destWidth, destHeight);
        operation.gravity("center");
        operation.background(toHexEncoding(BACKGROUND_COLOR));
        operation.extent(destWidth, destHeight);
        operation.quality((double) DEST_QUALITY);
        operation.addImage(srcFile.getPath());
        operation.addImage(destFile.getPath());
        if (type == Type.graphicsMagick) {
            ConvertCmd convertCmd = new ConvertCmd(true);
            if (graphicsMagickPath != null) {
                convertCmd.setSearchPath(graphicsMagickPath);
            }
            try {
                convertCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        } else {
            ConvertCmd convertCmd = new ConvertCmd(false);
            if (imageMagickPath != null) {
                convertCmd.setSearchPath(imageMagickPath);
            }
            try {
                convertCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:de.mprengemann.intellij.plugin.androidicons.images.ImageUtils.java

private static void verifyBorderImage(BufferedImage border) throws Wrong9PatchException {
    int[] rgb = border.getRGB(0, 0, border.getWidth(), border.getHeight(), null, 0, border.getWidth());
    for (int aRgb : rgb) {
        if ((0xff000000 & aRgb) != 0) {
            if (aRgb != 0xff000000 && aRgb != 0xffff0000) {
                throw new Wrong9PatchException();
            }/*from   ww  w. j ava2  s.  co m*/
        }
    }
}

From source file:de.mprengemann.intellij.plugin.androidicons.util.ImageUtils.java

private static BufferedImage resizeNormalImage(BufferedImage image, ImageInformation information)
        throws IOException {
    int newWidth = image.getWidth();
    int newHeight = image.getHeight();
    if (MathUtils.floatEquals(information.getFactor(), 1f)) {
        return image;
    }/*from   w  ww  .j  a va  2  s  .  c  om*/

    if (information.getFactor() >= 0) {
        newWidth = (int) (newWidth * information.getFactor());
        newHeight = (int) (newHeight * information.getFactor());
    }

    BufferedImage resizedImage = null;
    switch (information.getAlgorithm()) {
    case SCALR:
        Scalr.Method scalrMethod = (Scalr.Method) information.getMethod();
        resizedImage = Scalr.resize(image, scalrMethod, newWidth, newHeight, Scalr.OP_ANTIALIAS);
        break;
    case THUMBNAILATOR:
        return Thumbnails.of(image).size(newWidth, newHeight).asBufferedImage();
    }
    return resizedImage;
}