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:info.magnolia.cms.taglibs.util.TextToImageTag.java

/**
 * Create an image file that is a scaled version of the original image
 * @param the original BufferedImage/*w  w w  . ja  v a 2s.c  om*/
 * @param the scale factor
 * @return the new BufferedImage
 */
private BufferedImage scaleImage(BufferedImage oriImgBuff, double scaleFactor) {

    // get the dimesnions of the original image
    int oriWidth = oriImgBuff.getWidth();
    int oriHeight = oriImgBuff.getHeight();
    // get the width and height of the new image
    int newWidth = new Double(oriWidth * scaleFactor).intValue();
    int newHeight = new Double(oriHeight * scaleFactor).intValue();
    // create the thumbnail as a buffered image
    Image newImg = oriImgBuff.getScaledInstance(newWidth, newHeight, Image.SCALE_AREA_AVERAGING);
    BufferedImage newImgBuff = new BufferedImage(newImg.getWidth(null), newImg.getHeight(null),
            BufferedImage.TYPE_INT_RGB);
    Graphics2D g = newImgBuff.createGraphics();
    g.drawImage(newImg, 0, 0, null);
    g.dispose();
    // return the newImgBuff
    return newImgBuff;
}

From source file:com.flexive.shared.media.impl.FxMediaNativeEngine.java

public static BufferedImage scale(BufferedImage bi, int width, int height) {
    BufferedImage bi2;//from   w  ww. j  a v a  2s  .co m
    int scaleWidth = bi.getWidth(null);
    int scaleHeight = bi.getHeight(null);
    double scaleX = (double) width / scaleWidth;
    double scaleY = (double) height / scaleHeight;
    double scale = Math.min(scaleX, scaleY);
    scaleWidth = (int) ((double) scaleWidth * scale);
    scaleHeight = (int) ((double) scaleHeight * scale);
    Image scaledImage;
    if (HEADLESS) {
        // create a new buffered image, don't rely on a local graphics system (headless mode)
        final int type;
        if (bi.getType() != BufferedImage.TYPE_CUSTOM) {
            type = bi.getType();
        } else if (bi.getAlphaRaster() != null) {
            // alpha channel available
            type = BufferedImage.TYPE_INT_ARGB;
        } else {
            type = BufferedImage.TYPE_INT_RGB;
        }
        bi2 = new BufferedImage(scaleWidth, scaleHeight, type);
    } else {
        GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
                .getDefaultConfiguration();
        bi2 = gc.createCompatibleImage(scaleWidth, scaleHeight, bi.getTransparency());
    }
    Graphics2D g = bi2.createGraphics();
    if (scale < 0.3 && Math.max(scaleWidth, scaleHeight) < 500) {
        scaledImage = bi.getScaledInstance(scaleWidth, scaleHeight, Image.SCALE_SMOOTH);
        new ImageIcon(scaledImage).getImage();
        g.drawImage(scaledImage, 0, 0, scaleWidth, scaleHeight, null);
    } else {
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g.drawImage(bi, 0, 0, scaleWidth, scaleHeight, null);
    }
    g.dispose();
    return bi2;
}

From source file:com.celements.photo.image.GenerateThumbnail.java

public BufferedImage createThumbnail(BufferedImage img, OutputStream out, ImageDimensions imgSize,
        String watermark, String copyright, String type, Color defaultBg) {
    Image thumbImg = img;/*from w ww .  ja  v  a  2  s  .  co  m*/
    // Only generates a thumbnail if the image is larger than the desired thumbnail.
    mLogger.debug("img: " + img + " - imgSize: " + imgSize);
    if ((img.getWidth() > (int) imgSize.getWidth()) || (img.getHeight() > (int) imgSize.getHeight())) {
        // The "-1" is used to resize maintaining the aspect ratio.
        thumbImg = img.getScaledInstance((int) imgSize.getWidth(), -1, Image.SCALE_SMOOTH);
    }
    mLogger.debug("width ziel: " + imgSize.getWidth() + ", height ziel: " + imgSize.getHeight() + "; width: "
            + thumbImg.getWidth(null) + ", height: " + thumbImg.getHeight(null));
    BufferedImage buffThumb = convertImageToBufferedImage(thumbImg, watermark, copyright, defaultBg);
    encodeImage(out, buffThumb, img, type);
    return buffThumb;
}

From source file:org.jtrfp.trcl.core.ResourceManager.java

private BufferedImage[] getSpecialRAWImage(String name, Color[] palette, int upscalePowerOfTwo)
        throws IllegalAccessException, FileLoadException, IOException {
    RAWFile dat = getRAW(name);/*from  www.j  a  v  a 2 s . co m*/
    dat.setPalette(palette);
    BufferedImage[] segs = dat.asSegments(upscalePowerOfTwo);
    for (BufferedImage seg : segs) {
        Graphics g = seg.getGraphics();
        BufferedImage scaled = new BufferedImage(seg.getColorModel(), seg.copyData(null),
                seg.isAlphaPremultiplied(), null);
        g.drawImage(
                scaled.getScaledInstance(seg.getWidth() - 2, seg.getHeight() - 2, Image.SCALE_AREA_AVERAGING),
                1, 1, seg.getWidth() - 2, seg.getHeight() - 2, null);
        g.dispose();
    }
    return segs;
}

From source file:org.exist.launcher.Launcher.java

private boolean initSystemTray() {
    final Dimension iconDim = tray.getTrayIconSize();
    BufferedImage image = null;
    try {/*w w w  .ja  v a 2s.  c o m*/
        image = ImageIO.read(getClass().getResource("icon32.png"));
    } catch (final IOException e) {
        showMessageAndExit("Launcher failed", "Failed to read system tray icon.", false);
    }
    trayIcon = new TrayIcon(image.getScaledInstance(iconDim.width, iconDim.height, Image.SCALE_SMOOTH),
            "eXist-db Launcher");

    final JDialog hiddenFrame = new JDialog();
    hiddenFrame.setUndecorated(true);
    hiddenFrame.setIconImage(image);

    final PopupMenu popup = createMenu();
    trayIcon.setPopupMenu(popup);
    trayIcon.addActionListener(actionEvent -> {
        trayIcon.displayMessage(null, "Right click for menu", TrayIcon.MessageType.INFO);
        setServiceState();
    });

    // add listener for left click on system tray icon. doesn't work well on linux though.
    if (!SystemUtils.IS_OS_LINUX) {
        trayIcon.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent mouseEvent) {
                if (mouseEvent.getButton() == MouseEvent.BUTTON1) {
                    setServiceState();
                    hiddenFrame.add(popup);
                    popup.show(hiddenFrame, mouseEvent.getXOnScreen(), mouseEvent.getYOnScreen());
                }
            }
        });
    }

    try {
        hiddenFrame.setResizable(false);
        hiddenFrame.pack();
        hiddenFrame.setVisible(true);
        tray.add(trayIcon);
    } catch (final AWTException e) {
        return false;
    }

    return true;
}

From source file:View.Main.java

public void setData(String btnOption) {
    ArrayList<DataSet> dataset = downloader.getDataset();
    ArrayList<String> nameList = downloader.getNameList();

    if (dataset.size() == 0) {
        jLabel_txtDoctorName.setVisible(false);
        jLabel_txtHospitalContact.setVisible(false);
        jLabel_txtHospitalName.setVisible(false);

        jButton_next.setEnabled(false);/*from  w  w  w.  j  ava2 s .  c om*/
        jButton_prev.setEnabled(false);
    } else {
        jLabel_txtDoctorName.setVisible(true);
        jLabel_txtHospitalContact.setVisible(true);
        jLabel_txtHospitalName.setVisible(true);

        jButton_next.setEnabled(true);
        jButton_prev.setEnabled(true);
    }

    if (btnOption.toLowerCase().equals("start")) {
        cnt = 0;
    } else if (btnOption.toLowerCase().equals("next")) {
        cnt++;
    } else {
        cnt--;
    }

    if (cnt >= dataset.size()) {
        cnt = 0;
    } else if (cnt < 0) {
        cnt = dataset.size() - 1;
    }

    System.out.println("dataset size :" + dataset.size());

    if (dataset.size() > 1) {
        jLabel_doctorName.setText(dataset.get(cnt).getDoctorName());

        jLabel_hospitalName.setText(dataset.get(cnt).getHospitalName());
        jLabel_hospitalContact.setText(dataset.get(cnt).getHospitalContact());

        String imageA = Data.directoryPath_downloadNews + nameList.get(2 * cnt);
        String imageB = Data.directoryPath_downloadNews + nameList.get(2 * cnt + 1);
        System.out.println(imageA);

        File imageFileA = new File(imageA);
        File imageFileB = new File(imageB);

        BufferedImage bufImgA = null;
        BufferedImage bufImgB = null;

        try {
            bufImgA = ImageIO.read(imageFileA);
            bufImgB = ImageIO.read(imageFileB);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Image scaledImgA = bufImgA.getScaledInstance(jLabel_newsFeed_displayImageAfter.getWidth(),
                jLabel_newsFeed_displayImageAfter.getHeight(), Image.SCALE_DEFAULT);
        Image scaledImgB = bufImgB.getScaledInstance(jLabel_newsFeed_displayImageBefore.getWidth(),
                jLabel_newsFeed_displayImageBefore.getHeight(), Image.SCALE_DEFAULT);

        jLabel_newsFeed_displayImageAfter.setIcon(new ImageIcon(scaledImgA));
        jLabel_newsFeed_displayImageBefore.setIcon(new ImageIcon(scaledImgB));
    }
}

From source file:com.github.dactiv.fear.service.service.account.AccountService.java

/**
 * ??/* ww w  . j  a va 2s  . c  om*/
 *
 * @param sourcePath   ?
 * @param targetPath   ??
 * @param portraitSize ?
 *
 * @throws IOException
 */
private String scaleImage(String sourcePath, String targetPath, PortraitSize portraitSize) throws IOException {
    InputStream inputStream = new FileInputStream(sourcePath);

    BufferedImage source = ImageIO.read(inputStream);
    ColorModel targetColorModel = source.getColorModel();

    inputStream.close();

    int width = portraitSize.getWidth();
    int height = portraitSize.getHeight();

    BufferedImage target = new BufferedImage(targetColorModel,
            targetColorModel.createCompatibleWritableRaster(width, height),
            targetColorModel.isAlphaPremultiplied(), null);

    Image scaleImage = source.getScaledInstance(width, height, Image.SCALE_SMOOTH);

    Graphics2D g = target.createGraphics();
    g.drawImage(scaleImage, 0, 0, width, height, null);
    g.dispose();

    String result = targetPath + portraitSize.getName();
    FileOutputStream fileOutputStream = new FileOutputStream(result);
    ImageIO.write(target, PORTRAIT_PIC_TYPE, fileOutputStream);

    fileOutputStream.close();

    return result;
}

From source file:org.apache.roller.weblogger.business.jpa.JPAMediaFileManagerImpl.java

private void updateThumbnail(MediaFile mediaFile) {
    try {//w ww .  j  a va  2s.c  o  m
        FileContentManager cmgr = WebloggerFactory.getWeblogger().getFileContentManager();
        FileContent fc = cmgr.getFileContent(mediaFile.getWeblog(), mediaFile.getId());
        BufferedImage img = null;

        img = ImageIO.read(fc.getInputStream());

        // determine and save width and height
        mediaFile.setWidth(img.getWidth());
        mediaFile.setHeight(img.getHeight());
        strategy.store(mediaFile);

        int newWidth = mediaFile.getThumbnailWidth();
        int newHeight = mediaFile.getThumbnailHeight();

        // create thumbnail image
        Image newImage = img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
        BufferedImage tmp = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = tmp.createGraphics();
        g2.drawImage(newImage, 0, 0, newWidth, newHeight, null);
        g2.dispose();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(tmp, "png", baos);

        cmgr.saveFileContent(mediaFile.getWeblog(), mediaFile.getId() + "_sm",
                new ByteArrayInputStream(baos.toByteArray()));

    } catch (Exception e) {
        log.debug("ERROR creating thumbnail", e);
    }
}

From source file:pcd3.View.java

private void pilihGambarLoroMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pilihGambarLoroMouseClicked
    final String path = "./Citra Images/form.1";

    javax.swing.JFileChooser chooser = new javax.swing.JFileChooser();
    chooser.setCurrentDirectory(new File(path));

    chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
        public final static String jpeg = "jpeg";
        public final String jpg = "jpg";
        public final String gif = "gif";
        public final String tiff = "tiff";
        public final String tif = "tif";
        public final String png = "png";

        /*Get the extension of a file.*/
        public String getExtension(java.io.File f) {
            String ext = null;/*  ww  w.jav  a  2  s  . c om*/
            String s = f.getName();
            int i = s.lastIndexOf('.');

            if (i > 0 && i < s.length() - 1) {
                ext = s.substring(i + 1).toLowerCase();
            }
            return ext;
        }

        @Override
        public String getDescription() {
            return "All Images extensions (jpg, gif, tiff, tif, png)";
        }

        @Override
        public boolean accept(java.io.File f) {
            if (f.isDirectory()) {
                return true;
            }

            String extension = getExtension(f);
            if (extension != null) {
                return extension.equals(tiff) || extension.equals(tif) || extension.equals(gif)
                        || extension.equals(jpeg) || extension.equals(jpg) || extension.equals(png);
            }

            return false;
        }
    });

    if (chooser.showDialog(this, "  Open  ") == javax.swing.JFileChooser.APPROVE_OPTION) {
        java.io.File file = chooser.getSelectedFile();
        String filePath = file.toString();
        try {
            final BufferedImage bimg = ImageIO.read(new File(filePath));
            namaCitraLoro.setText("Nama Citra : " + file.getName());
            Thread t = new Thread() {
                @Override
                public void run() {
                    imageFormLoro.setImage(bimg);
                    imageFormLoro.imageToGray(1);
                    citraSmoothingAwal.setText("");
                    citraSmoothingGray.setText("");
                    citraSmoothingHasil.setText("");
                    citraSmoothingAwal.setIcon(new ImageIcon(bimg.getScaledInstance(300, 300, 0)));
                    citraSmoothingGray.setIcon(
                            new ImageIcon(imageFormLoro.getGrayImage().getScaledInstance(300, 300, 0)));
                    ukuranCitraLoro.setText("Ukuran Citra : " + imageFormLoro.getTinggi() + " x "
                            + imageFormLoro.getLebar() + "");
                    imageFormLoro.setSmoothingImage();
                    citraSmoothingHasil.setIcon(
                            new ImageIcon(imageFormLoro.getSmoothingImage().getScaledInstance(300, 300, 0)));
                }
            };
            t.start();

        } catch (IOException e) {
            javax.swing.JOptionPane.showMessageDialog(this, "File Tidak Ditemukan " + e);
        }
    }
}

From source file:pcd3.View.java

private void pilihGambarSharpMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pilihGambarSharpMouseClicked
    final String path = "./Citra Images/form.1";

    javax.swing.JFileChooser chooser = new javax.swing.JFileChooser();
    chooser.setCurrentDirectory(new File(path));

    chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
        public final static String jpeg = "jpeg";
        public final String jpg = "jpg";
        public final String gif = "gif";
        public final String tiff = "tiff";
        public final String tif = "tif";
        public final String png = "png";

        /*Get the extension of a file.*/
        public String getExtension(java.io.File f) {
            String ext = null;/*  w  w w.  j a v  a  2 s .co  m*/
            String s = f.getName();
            int i = s.lastIndexOf('.');

            if (i > 0 && i < s.length() - 1) {
                ext = s.substring(i + 1).toLowerCase();
            }
            return ext;
        }

        @Override
        public String getDescription() {
            return "All Images extensions (jpg, gif, tiff, tif, png)";
        }

        @Override
        public boolean accept(java.io.File f) {
            if (f.isDirectory()) {
                return true;
            }

            String extension = getExtension(f);
            if (extension != null) {
                return extension.equals(tiff) || extension.equals(tif) || extension.equals(gif)
                        || extension.equals(jpeg) || extension.equals(jpg) || extension.equals(png);
            }

            return false;
        }
    });

    if (chooser.showDialog(this, "  Open  ") == javax.swing.JFileChooser.APPROVE_OPTION) {
        java.io.File file = chooser.getSelectedFile();
        String filePath = file.toString();
        try {
            final BufferedImage bimg = ImageIO.read(new File(filePath));
            namaCitraTelu.setText("Nama Citra : " + file.getName());
            Thread t = new Thread() {
                @Override
                public void run() {
                    imageFormTelu.setImage(bimg);
                    imageFormTelu.imageToGray(1);
                    citraSharpheningAwal.setText("");
                    citraSharpheningGray.setText("");
                    citraSharpheningHasil.setText("");
                    citraSharpheningAwal.setIcon(new ImageIcon(bimg.getScaledInstance(300, 300, 0)));
                    citraSharpheningGray.setIcon(
                            new ImageIcon(imageFormTelu.getGrayImage().getScaledInstance(300, 300, 0)));
                    ukuranCitraTelu.setText("Ukuran Citra : " + imageFormTelu.getTinggi() + " x "
                            + imageFormTelu.getLebar() + "");
                    imageFormTelu.setSharpeningImage();
                    citraSharpheningHasil.setIcon(
                            new ImageIcon(imageFormTelu.getSharpeningImage().getScaledInstance(300, 300, 0)));
                }
            };
            t.start();

        } catch (IOException e) {
            javax.swing.JOptionPane.showMessageDialog(this, "File Tidak Ditemukan " + e);
        }
    }
}