Example usage for java.awt.image BufferedImage getScaledInstance

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

Introduction

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

Prototype

public Image getScaledInstance(int width, int height, int hints) 

Source Link

Document

Creates a scaled version of this image.

Usage

From source file:View.EmbedFile.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & GIF Images", "jpg", "gif");

    chooser.setFileFilter(filter);/* w w  w  .  j av  a 2  s  .  c  o  m*/
    int returnVal = chooser.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        String path = chooser.getSelectedFile().getPath();
        jLabel2.setText(chooser.getSelectedFile().getName());
        String masterKeyBackUpName = System.currentTimeMillis() + "."
                + FilenameUtils.getExtension(chooser.getSelectedFile().getPath());
        String masterKeyBackUpLocation = Configuration.masterPoolLocation + masterKeyBackUpName;
        masterFileName = masterKeyBackUpName;
        try {
            FileUtils.copyFile(chooser.getSelectedFile(), new File(masterKeyBackUpLocation));
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("You chose to open this file: " + path);
        BufferedImage img = null;
        try {
            img = ImageIO.read(new File(path));
            Image scaledInstance = img.getScaledInstance(jLabel2.getWidth(), jLabel2.getHeight(),
                    Image.SCALE_SMOOTH);
            ImageIcon imageIcon = new ImageIcon(scaledInstance);
            jLabel2.setIcon(imageIcon);
            analyze_master_file_button.setEnabled(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        long size = (chooser.getSelectedFile().length()) / 1024;

        Dbcon dbcon = new Dbcon();
        int ins = dbcon.insert(
                "insert into tbl_encryption_log(user_id,master_file,master_file_size,encryption_type)values('"
                        + Login.logged_in_user_id + "','" + path + "','" + size + "',1)");
        if (ins > 0) {
            ResultSet rs = dbcon.select("select max(process_id)  from tbl_encryption_log");
            try {
                if (rs.next()) {
                    System.out.println(rs.getString(1));
                    EmbedFile.process_id = Integer.parseInt(rs.getString(1));
                    System.out.println(EmbedFile.process_id);

                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

}

From source file:iqq.app.ui.manager.MainManager.java

private Image getTrayFace(IMEntity owner) {
    BufferedImage avatar = null;
    if (owner.getAvatar() != null) {
        avatar = owner.getAvatarBuffered();
    } else {//from w  w w . j a v a2 s .c om
        avatar = UIUtils.getDefaultAvatarBuffer();
    }
    return avatar.getScaledInstance(32, 32, 100);
}

From source file:com.github.cmisbox.ui.BaseFrame.java

public Image getImage(String resource, Integer height, Integer width) {
    try {/*from  w  w w.  ja v a 2s.  c om*/

        BufferedImage image = ImageIO.read(this.getClass().getResource(resource));

        if ((height != null) && (width != null)
                && ((image.getHeight() != height) || (image.getWidth() != width))) {
            return image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        }

        return image;
    } catch (IOException e1) {
        this.log.error(e1);
    }
    return null;
}

From source file:View.EmbedMessage.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & GIF Images", "jpg", "gif");

    chooser.setFileFilter(filter);//  w w w.j  a va2  s. com
    int returnVal = chooser.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        String path = chooser.getSelectedFile().getPath();

        try {
            String masterKeyBackUpName = System.currentTimeMillis() + "."
                    + FilenameUtils.getExtension(chooser.getSelectedFile().getPath());
            String masterKeyBackUpLocation = Configuration.masterPoolLocation + masterKeyBackUpName;
            masterFileName = masterKeyBackUpName;
            FileUtils.copyFile(chooser.getSelectedFile(), new File(masterKeyBackUpLocation));

            image_name.setText(chooser.getSelectedFile().getName());
            System.out.println("You chose to open this file: " + path);
            BufferedImage img = null;
            try {
                img = ImageIO.read(new File(path));
                Image scaledInstance = img.getScaledInstance(image_Label.getWidth(), image_Label.getHeight(),
                        Image.SCALE_SMOOTH);
                ImageIcon imageIcon = new ImageIcon(scaledInstance);
                image_Label.setIcon(imageIcon);
            } catch (IOException e) {
                e.printStackTrace();
            }
            long size = (chooser.getSelectedFile().length()) / 1024;

            Dbcon dbcon = new Dbcon();
            int ins = dbcon
                    .insert("insert into tbl_encryption_log(user_id,master_file,master_file_size)values('"
                            + Login.logged_in_user_id + "','" + masterKeyBackUpName + "','" + size + "')");
            if (ins > 0) {
                ResultSet rs = dbcon.select("select max(process_id)  from tbl_encryption_log");
                try {
                    if (rs.next()) {
                        System.out.println(rs.getString(1));
                        EmbedMessage.process_id = Integer.parseInt(rs.getString(1));
                        System.out.println(EmbedMessage.process_id);
                        analyze_button.setEnabled(true);
                    }
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.jamwiki.utils.ImageUtil.java

/**
 * Resize an image, using a maximum dimension value.  Image dimensions will
 * be constrained so that the proportions are the same, but neither the width
 * or height exceeds the value specified.
 *///  w  w w . j  a  v  a2  s .  c  om
private static BufferedImage resizeImage(WikiImage wikiImage, int maxDimension) throws Exception {
    File imageFile = new File(Environment.getValue(Environment.PROP_FILE_DIR_FULL_PATH), wikiImage.getUrl());
    BufferedImage original = ImageUtil.loadImage(imageFile);
    maxDimension = calculateImageIncrement(maxDimension);
    int increment = Environment.getIntValue(Environment.PROP_IMAGE_RESIZE_INCREMENT);
    if (increment <= 0 || (maxDimension > original.getWidth() && maxDimension > original.getHeight())) {
        // let the browser scale the image
        return original;
    }
    String newUrl = wikiImage.getUrl();
    int pos = newUrl.lastIndexOf('.');
    if (pos > -1) {
        newUrl = newUrl.substring(0, pos) + "-" + maxDimension + "px" + newUrl.substring(pos);
    } else {
        newUrl += "-" + maxDimension + "px";
    }
    wikiImage.setUrl(newUrl);
    File newImageFile = new File(Environment.getValue(Environment.PROP_FILE_DIR_FULL_PATH), newUrl);
    if (newImageFile.exists()) {
        return ImageUtil.loadImage(newImageFile);
    }
    int width = -1;
    int height = -1;
    if (original.getWidth() >= original.getHeight()) {
        width = maxDimension;
    } else {
        height = maxDimension;
    }
    Image resized = null;
    try {
        resized = original.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
    } catch (Throwable t) {
        logger.severe(
                "Unable to resize image.  This problem sometimes occurs due to dependencies between Java and X on UNIX systems.  Consider enabling an X server or setting the java.awt.headless parameter to true for your JVM.",
                t);
        resized = original;
    }
    BufferedImage bufferedImage = null;
    if (resized instanceof BufferedImage) {
        bufferedImage = (BufferedImage) resized;
    } else {
        bufferedImage = ImageUtil.imageToBufferedImage(resized);
    }
    ImageUtil.saveImage(bufferedImage, newImageFile);
    return bufferedImage;
}

From source file:de.romankreisel.faktotum.beans.BundesbruderBean.java

/**
 * @param originalPicture/*  ww  w .  ja  v a 2  s  .c  om*/
 * @param pictureHeight
 * @param pictureWidth
 * @return
 * @throws IOException
 */
public Byte[] resizeProfilePicture(Byte[] originalPicture, int width, int height) throws IOException {
    BufferedImage originalImage = this.getImageFromByteArray(originalPicture);
    Dimension newDimension = this.getScaledDimension(
            new Dimension(originalImage.getWidth(), originalImage.getHeight()), new Dimension(width, height));
    Image scaledImage = originalImage.getScaledInstance(newDimension.width, newDimension.height,
            Image.SCALE_SMOOTH);
    return this.storeImageToByteArray(scaledImage);
}

From source file:com.galenframework.utils.GalenUtils.java

/**
 * Check the devicePixelRatio and adapts the size of the screenshot as if the ratio was 1.0
 * @param driver//from   w  w w .j av  a  2  s. co m
 * @param screenshotImage
 * @return
 */
public static BufferedImage resizeScreenshotIfNeeded(WebDriver driver, BufferedImage screenshotImage) {
    Double devicePixelRatio = ((Number) ((JavascriptExecutor) driver)
            .executeScript(JS_RETRIEVE_DEVICE_PIXEL_RATIO)).doubleValue();

    if (devicePixelRatio > 1.0 && screenshotImage.getWidth() > 0) {
        Long screenSize = (Long) ((JavascriptExecutor) driver).executeScript(
                "return Math.max(" + "document.body.scrollWidth, document.documentElement.scrollWidth,"
                        + "document.body.offsetWidth, document.documentElement.offsetWidth,"
                        + "document.body.clientWidth, document.documentElement.clientWidth);");

        Double estimatedPixelRatio = ((double) screenshotImage.getWidth()) / ((double) screenSize);

        if (estimatedPixelRatio > 1.0) {

            int newWidth = (int) (screenshotImage.getWidth() / estimatedPixelRatio);
            int newHeight = (int) (screenshotImage.getHeight() / estimatedPixelRatio);

            Image tmp = screenshotImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
            BufferedImage scaledImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);

            Graphics2D g2d = scaledImage.createGraphics();
            g2d.drawImage(tmp, 0, 0, null);
            g2d.dispose();

            return scaledImage;
        } else
            return screenshotImage;
    } else
        return screenshotImage;
}

From source file:de.anycook.upload.UploadHandler.java

/**
 * speichert eine kleine Version des Bildes
 *
 * @param image    BufferedImage// w w  w.  j av  a  2s . c  om
 * @param filename Name der zu erzeugenden Datei
 */
private void saveSmallImage(BufferedImage image, String filename) throws IOException {
    int height = image.getHeight();
    int width = image.getWidth();
    double imageRatio = (double) width / (double) height;

    int xtranslate = 0;
    int ytranslate = 0;

    if (imageRatio > 1) {
        xtranslate = (width - height) / 2;
    } else {
        ytranslate = (height - width) / 2;
    }

    BufferedImage tempImage = image.getSubimage(xtranslate, ytranslate, width - xtranslate * 2,
            height - ytranslate * 2);
    BufferedImage newImage = new BufferedImage(smallSize, smallSize, BufferedImage.TYPE_INT_RGB);
    newImage.getGraphics().drawImage(tempImage.getScaledInstance(smallSize, smallSize, Image.SCALE_SMOOTH), 0,
            0, null);

    imageSaver.save("small/", filename, newImage);
}

From source file:com.actionbazaar.controller.SellController.java

/**
 * Saves the uploaded file into a folder for the user.
 * @param imageFile - image file to be saved
 * @return image id/*from ww w. jav a  2 s  .c om*/
 */
private String save(UploadedFile imageFile) {
    try {
        File saveFld = new File(imageFolder + File.separator + userDisplay.getUser().getUsername());
        if (!saveFld.exists()) {
            if (!saveFld.mkdir()) {
                logger.log(Level.INFO, "Unable to create folder: {0}", saveFld.getAbsolutePath());
                return null;
            }
        }
        File tmp = File.createTempFile("img", "img");
        IOUtils.copy(imageFile.getInputstream(), new FileOutputStream(tmp));
        File thumbnailImage = new File(saveFld + File.separator + UUID.randomUUID().toString() + ".png");
        File fullResolution = new File(saveFld + File.separator + UUID.randomUUID().toString() + ".png");

        // Create the thumbnail
        BufferedImage image = ImageIO.read(tmp);
        Image thumbnailIm = image.getScaledInstance(310, 210, Image.SCALE_SMOOTH);
        // Convert the thumbnail java.awt.Image into a rendered image which we can save
        BufferedImage thumbnailBi = new BufferedImage(thumbnailIm.getWidth(null), thumbnailIm.getHeight(null),
                BufferedImage.TYPE_INT_RGB);
        Graphics bg = thumbnailBi.getGraphics();
        bg.drawImage(thumbnailIm, 0, 0, null);
        bg.dispose();

        ImageIO.write(thumbnailBi, "png", thumbnailImage);
        // Write out the full resolution image as a thumbnail
        ImageIO.write(image, "png", fullResolution);
        if (!tmp.delete()) {
            logger.log(Level.INFO, "Unable to delete: {0}", tmp.getAbsolutePath());
        }
        String imageId = UUID.randomUUID().toString();
        imageBean.addImage(imageId, new ImageRecord(imageFile.getFileName(), fullResolution.getAbsolutePath(),
                thumbnailImage.getAbsolutePath(), userDisplay.getUser().getUsername()));
        return imageId;
    } catch (Throwable t) {
        logger.log(Level.SEVERE, "Unable to save the image.", t);
        return null;
    }
}

From source file:com.mycompany.controllers.ClubController.java

private byte[] LogoConvertion(byte[] bytes) {
    int width = 200;
    int height = 200;
    ByteArrayInputStream in = new ByteArrayInputStream(bytes);
    try {/*from  w ww.  j av  a 2s.  com*/
        BufferedImage img = ImageIO.read(in);
        if (height == 0) {
            height = (width * img.getHeight()) / img.getWidth();
        }
        if (width == 0) {
            width = (height * img.getWidth()) / img.getHeight();
        }
        Image scaledImage = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage imageBuff = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        imageBuff.getGraphics().drawImage(scaledImage, 0, 0, new Color(0, 0, 0), null);

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        ImageIO.write(imageBuff, "jpg", buffer);

        bytes = buffer.toByteArray();
    } catch (IOException e) {
        log.error("File convertion error");
    }
    return bytes;
}