Example usage for java.awt Image getWidth

List of usage examples for java.awt Image getWidth

Introduction

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

Prototype

public abstract int getWidth(ImageObserver observer);

Source Link

Document

Determines the width of the image.

Usage

From source file:org.jtalks.common.web.validation.ImageDimensionValidator.java

/**
 * Validate object with {@link ImageDimension} annotation.
 *
 * @param multipartFile image that user want upload as avatar
 * @param context       validation context
 * @return {@code true} if validation successfull or false if fails
 *//*from  w w w .j  a  v a  2s .  c  o m*/
@Override
public boolean isValid(MultipartFile multipartFile, ConstraintValidatorContext context) {
    if (multipartFile.isEmpty()) {
        //assume that empty multipart file is valid to avoid validation message when user doesn't load nothing
        return true;
    }
    Image image;
    try {
        image = ImageIO.read(multipartFile.getInputStream());
    } catch (Exception e) {
        return false;
    }
    return (image == null) ? false : image.getWidth(null) == imageWidth && image.getHeight(null) == imageHeight;
}

From source file:com.krawler.esp.handlers.FileUploadHandler.java

private BufferedImage toBufferedImage(Image image, int type) {
    image = new ImageIcon(image).getImage();
    BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
    Graphics g = bufferedImage.createGraphics();
    if (type == BufferedImage.TYPE_INT_RGB) {
        g.setColor(Color.white);//from w  w w.j  a v  a2s.  co  m
        g.fillRect(0, 0, image.getWidth(null), image.getHeight(null));
    }
    g.drawImage(image, 0, 0, null);
    g.dispose();

    return bufferedImage;
}

From source file:org.colombbus.tangara.AboutWindow.java

public AboutWindow(JFrame frame, Image baseHeaderImage) {
    super(frame, true);
    windowWidth = baseHeaderImage.getWidth(null);
    windowHeight = baseHeaderImage.getHeight(null);
    setLocationAndSize();/*from  w w  w  .  j a  v a 2s . c om*/
    initialize(baseHeaderImage);
}

From source file:Thumbnail.java

/**
* Reads an image in a file and creates a thumbnail in another file.
* largestDimension is the largest dimension of the thumbnail, the other dimension is scaled accordingly.
* Utilises weighted stepping method to gradually reduce the image size for better results,
* i.e. larger steps to start with then smaller steps to finish with.
* Note: always writes a JPEG because GIF is protected or something - so always make your outFilename end in 'jpg'.
* PNG's with transparency are given white backgrounds
*///from   ww w .j  ava  2  s  .co  m
public String createThumbnail(String inFilename, String outFilename, int largestDimension) {
    try {
        double scale;
        int sizeDifference, originalImageLargestDim;
        if (!inFilename.endsWith(".jpg") && !inFilename.endsWith(".jpeg") && !inFilename.endsWith(".gif")
                && !inFilename.endsWith(".png")) {
            return "Error: Unsupported image type, please only either JPG, GIF or PNG";
        } else {
            Image inImage = Toolkit.getDefaultToolkit().getImage(inFilename);
            if (inImage.getWidth(null) == -1 || inImage.getHeight(null) == -1) {
                return "Error loading file: \"" + inFilename + "\"";
            } else {
                //find biggest dimension       
                if (inImage.getWidth(null) > inImage.getHeight(null)) {
                    scale = (double) largestDimension / (double) inImage.getWidth(null);
                    sizeDifference = inImage.getWidth(null) - largestDimension;
                    originalImageLargestDim = inImage.getWidth(null);
                } else {
                    scale = (double) largestDimension / (double) inImage.getHeight(null);
                    sizeDifference = inImage.getHeight(null) - largestDimension;
                    originalImageLargestDim = inImage.getHeight(null);
                }
                //create an image buffer to draw to
                BufferedImage outImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); //arbitrary init so code compiles
                Graphics2D g2d;
                AffineTransform tx;
                if (scale < 1.0d) //only scale if desired size is smaller than original
                {
                    int numSteps = sizeDifference / 100;
                    int stepSize = sizeDifference / numSteps;
                    int stepWeight = stepSize / 2;
                    int heavierStepSize = stepSize + stepWeight;
                    int lighterStepSize = stepSize - stepWeight;
                    int currentStepSize, centerStep;
                    double scaledW = inImage.getWidth(null);
                    double scaledH = inImage.getHeight(null);
                    if (numSteps % 2 == 1) //if there's an odd number of steps
                        centerStep = (int) Math.ceil((double) numSteps / 2d); //find the center step
                    else
                        centerStep = -1; //set it to -1 so it's ignored later
                    Integer intermediateSize = originalImageLargestDim,
                            previousIntermediateSize = originalImageLargestDim;
                    Integer calculatedDim;
                    for (Integer i = 0; i < numSteps; i++) {
                        if (i + 1 != centerStep) //if this isn't the center step
                        {
                            if (i == numSteps - 1) //if this is the last step
                            {
                                //fix the stepsize to account for decimal place errors previously
                                currentStepSize = previousIntermediateSize - largestDimension;
                            } else {
                                if (numSteps - i > numSteps / 2) //if we're in the first half of the reductions
                                    currentStepSize = heavierStepSize;
                                else
                                    currentStepSize = lighterStepSize;
                            }
                        } else //center step, use natural step size
                        {
                            currentStepSize = stepSize;
                        }
                        intermediateSize = previousIntermediateSize - currentStepSize;
                        scale = (double) intermediateSize / (double) previousIntermediateSize;
                        scaledW = (int) scaledW * scale;
                        scaledH = (int) scaledH * scale;
                        outImage = new BufferedImage((int) scaledW, (int) scaledH, BufferedImage.TYPE_INT_RGB);
                        g2d = outImage.createGraphics();
                        g2d.setBackground(Color.WHITE);
                        g2d.clearRect(0, 0, outImage.getWidth(), outImage.getHeight());
                        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                        tx = new AffineTransform();
                        tx.scale(scale, scale);
                        g2d.drawImage(inImage, tx, null);
                        g2d.dispose();
                        inImage = new ImageIcon(outImage).getImage();
                        previousIntermediateSize = intermediateSize;
                    }
                } else {
                    //just copy the original
                    outImage = new BufferedImage(inImage.getWidth(null), inImage.getHeight(null),
                            BufferedImage.TYPE_INT_RGB);
                    g2d = outImage.createGraphics();
                    g2d.setBackground(Color.WHITE);
                    g2d.clearRect(0, 0, outImage.getWidth(), outImage.getHeight());
                    tx = new AffineTransform();
                    tx.setToIdentity(); //use identity matrix so image is copied exactly
                    g2d.drawImage(inImage, tx, null);
                    g2d.dispose();
                }
                //JPEG-encode the image and write to file.
                OutputStream os = new FileOutputStream(outFilename);
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
                encoder.encode(outImage);
                os.close();
            }
        }
    } catch (Exception ex) {
        String errorMsg = "";
        errorMsg += "<br>Exception: " + ex.toString();
        errorMsg += "<br>Cause = " + ex.getCause();
        errorMsg += "<br>Stack Trace = ";
        StackTraceElement stackTrace[] = ex.getStackTrace();
        for (int traceLine = 0; traceLine < stackTrace.length; traceLine++) {
            errorMsg += "<br>" + stackTrace[traceLine];
        }
        return errorMsg;
    }
    return ""; //success
}

From source file:org.colombbus.tangara.AboutWindow.java

private BufferedImage createBackgroundImage(Image baseBackgroundImg) {
    BufferedImage newImg = new BufferedImage(baseBackgroundImg.getWidth(null),
            baseBackgroundImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
    newImg.getGraphics().drawImage(baseBackgroundImg, 0, 0, null);
    Graphics2D drawingGraphics = (Graphics2D) newImg.getGraphics();
    Color titleColor = Configuration.instance().getColor("tangara.title.color");
    String titleText = Configuration.instance().getString("tangara.title");
    Font titleFont = Configuration.instance().getFont("tangara.title.font");
    drawingGraphics.setFont(titleFont);/* w  ww  .  ja va2 s  .  com*/
    drawingGraphics.setColor(titleColor);
    drawingGraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    drawingGraphics.drawString(titleText, marginLeft, windowHeight / 2 - marginText);
    return newImg;
}

From source file:net.sf.jasperreports.engine.JRImageRenderer.java

@Override
public Dimension2D getDimension(JasperReportsContext jasperReportsContext) throws JRException {
    Image img = getImage(jasperReportsContext);
    return new Dimension(img.getWidth(null), img.getHeight(null));
}

From source file:org.kitodo.imagemanagement.ImageManagementIT.java

@Test
public void testGetScaledWebImage() throws IOException, InfoException {
    assert new File(_00000001_TIF).exists();
    ImageManagementInterface module = new ImageManagement();
    Image scaledWebImage = module.getScaledWebImage(new File(_00000001_TIF).toURI(), 0.3);
    assertEquals((int) Math.round(0.3 * new Info(_00000001_TIF, true).getImageWidth()),
            scaledWebImage.getWidth(null));
}

From source file:com.krawler.esp.handlers.genericFileUpload.java

private BufferedImage toBufferedImage(Image image) {
    image = new ImageIcon(image).getImage();
    BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null),
            BufferedImage.TYPE_INT_RGB);
    Graphics g = bufferedImage.createGraphics();
    g.setColor(Color.white);/*from w  ww.java2 s. com*/
    g.fillRect(0, 0, image.getWidth(null), image.getHeight(null));
    g.drawImage(image, 0, 0, null);
    g.dispose();

    return bufferedImage;
}

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

public String compressPic() {
    try {/*from w w w  .j  a  v a 2  s . c  o  m*/
        // ?
        file = new File(inputDir);
        //System.out.println(inputDir + inputFileName);
        if (!file.exists()) {
            //throw new Exception("?");
        }
        Image img = ImageIO.read(file);
        // ??
        if (img.getWidth(null) == -1) {
            System.out.println(" can't read,retry!" + "<BR>");
            return "no";
        } else {
            int newWidth;
            int newHeight;
            // ?
            if (this.proportion == true) {
                // ?
                double rate1 = ((double) img.getWidth(null)) / (double) outputWidth + 0.1;
                double rate2 = ((double) img.getHeight(null)) / (double) outputHeight + 0.1;
                // ?
                double rate = rate1 > rate2 ? rate1 : rate2;
                newWidth = (int) (((double) img.getWidth(null)) / rate);
                newHeight = (int) (((double) img.getHeight(null)) / rate);
            } else {
                newWidth = outputWidth; // 
                newHeight = outputHeight; // 
            }
            BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);

            /*
             * Image.SCALE_SMOOTH  ?  ?? 
             */
            tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0,
                    null);
            File f = new File(outputDir);
            if (!f.exists()) {
                f.mkdirs();
            }
            FileOutputStream out = new FileOutputStream(outputDir + outputFileName);
            // JPEGImageEncoder??
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(tag);
            out.close();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return "ok";
}

From source file:com.krawler.esp.handlers.genericFileUpload.java

private BufferedImage toBufferedCompanyImage(Image image) {
    image = new ImageIcon(image).getImage();
    BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null),
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = bufferedImage.createGraphics();
    //       java.awt.Color transparent = new java.awt.Color(255, 255, 255, 1);
    //                g.setColor(transparent);
    //                int rule = java.awt.AlphaComposite.SRC_OVER;
    //                        
    //                java.awt.AlphaComposite ac = java.awt.AlphaComposite.getInstance(rule,1);
    //                g.setComposite(ac);
    //      g.fillRect(0, 0, image.getWidth(null), image.getHeight(null));
    g.drawImage(image, 0, 0, null);//w w  w . ja v a  2 s.c  o  m
    g.dispose();

    return bufferedImage;
}