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:edu.harvard.iq.dvn.core.web.servlet.FileDownloadServlet.java

private boolean generateImageThumb(StudyFile file) {

    String fileLocation = file.getFileSystemLocation();
    if (fileLocation == null || fileLocation.trim().equals("")) {
        return false;
    }/*ww w .  j a v a  2 s.c  om*/
    String thumbFileLocation = fileLocation + ".thumb";

    // see if the thumb is already generated and saved:

    if (new File(thumbFileLocation).exists()) {
        return true;
    }

    // let's attempt to generate the thumb:

    // the default size of the thumbnail is 64 pixels horizontally.
    // The number 64 was picked arbitrarily; if a different size is 
    // desired, it can be configured via the dvn.image.thumbnail.size 
    // JVM option.

    Long thumbSize = Long.valueOf(64);

    String thumbSizeOption = System.getProperty("dvn.image.thumbnail.size");

    if (thumbSizeOption != null) {
        Long thumbSizeOptionValue = null;
        try {
            thumbSizeOptionValue = new Long(thumbSizeOption);
        } catch (NumberFormatException nfe) {
            // if the supplied option value is invalid/unparseable, we
            // ignore it and fall back to the default value. 
        }
        if (thumbSizeOptionValue != null && thumbSizeOptionValue.longValue() > 0) {
            thumbSize = thumbSizeOptionValue;
        }
    }

    // it is also possible to configure the thumbnail size for a 
    // specific dataverse: 

    VDC vdc = file.getStudy().getOwner();

    if (vdc != null) {
        thumbSizeOption = System.getProperty("dvn.image.thumbnail.size." + vdc.getAlias());

        if (thumbSizeOption != null) {
            Long thumbSizeOptionValue = null;
            try {
                thumbSizeOptionValue = new Long(thumbSizeOption);
            } catch (NumberFormatException nfe) {
                // if the supplied option value is invalid/unparseable, we
                // ignore it and fall back to the default value. 
            }
            if (thumbSizeOptionValue != null && thumbSizeOptionValue.longValue() > 0) {
                thumbSize = thumbSizeOptionValue;
            }
        }
    }

    // This is the default location of the "convert" executable from the
    // ImageMagick package. If it's installed in a different locaiton, 
    // it can be configured via the dvn.image.convert.exec JVM option. 

    String imageMagickConvertExec = "/usr/bin/convert";

    String imageMagickConvertExecOption = System.getProperty("dvn.image.convrt.exec");

    if (imageMagickConvertExecOption != null) {
        if (!imageMagickConvertExecOption.trim().equals("")) {
            imageMagickConvertExec = imageMagickConvertExecOption.trim();
        }
    }

    if (new File(imageMagickConvertExec).exists()) {
        String sizeOption = " -size " + thumbSize + "x" + thumbSize + " ";

        String ImageMagickCommandLine = imageMagickConvertExec + sizeOption + fileLocation + " -resize "
                + thumbSize + " -flatten png:" + thumbFileLocation;
        int exitValue = 1;

        try {
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec(ImageMagickCommandLine);
            exitValue = process.waitFor();
        } catch (Exception e) {
            exitValue = 1;
        }

        if (exitValue == 0) {
            return true;
        }
    }

    // For whatever reason, creating the thumbnail with ImageMagick
    // has failed.
    // Let's try again, this time with Java's standard Image
    // library:

    try {
        BufferedImage fullSizeImage = ImageIO.read(new File(fileLocation));

        if (fullSizeImage == null) {
            return false;
        }

        double scaleFactor = (thumbSize.doubleValue()) / (double) fullSizeImage.getWidth(null);
        int thumbHeight = (int) (fullSizeImage.getHeight(null) * scaleFactor);

        // We are willing to spend a few extra CPU cycles to generate
        // better-looking thumbnails, hence the SCALE_SMOOTH flag. 
        // SCALE_FAST would trade quality for speed. 

        java.awt.Image thumbImage = fullSizeImage.getScaledInstance(thumbSize.intValue(), thumbHeight,
                java.awt.Image.SCALE_SMOOTH);

        ImageWriter writer = null;
        Iterator iter = ImageIO.getImageWritersByFormatName("png");
        if (iter.hasNext()) {
            writer = (ImageWriter) iter.next();
        } else {
            return false;
        }

        BufferedImage lowRes = new BufferedImage(thumbSize.intValue(), thumbHeight, BufferedImage.TYPE_INT_RGB);
        lowRes.getGraphics().drawImage(thumbImage, 0, 0, null);

        ImageOutputStream ios = ImageIO.createImageOutputStream(new File(thumbFileLocation));
        writer.setOutput(ios);

        // finally, save thumbnail image:
        writer.write(lowRes);
        writer.dispose();

        ios.close();
        thumbImage.flush();
        fullSizeImage.flush();
        lowRes.flush();
        return true;
    } catch (Exception e) {
        // something went wrong, returning "false":
        dbgLog.info("ImageIO: caught an exception while trying to generate a thumbnail for " + fileLocation);

        return false;
    }
}

From source file:pcd3.View.java

private void pilihGambarCitraMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pilihGambarCitraMouseClicked
    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;/*from ww  w  . j av a2  s. com*/
            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));
            namaCitra.setText("Nama Citra : " + file.getName());
            Thread t = new Thread() {
                @Override
                public void run() {
                    imageFormSiji.setImage(bimg);
                    imageFormSiji.imageToGray(1);
                    imageFormSiji.setHistogram();
                    int jumlah = 0;
                    DefaultCategoryDataset chartBarAwal = new DefaultCategoryDataset();
                    DefaultCategoryDataset chartBarHasil = new DefaultCategoryDataset();
                    //barChartData.setva
                    for (int i = 0; i < imageFormSiji.getHistogram().size(); i++) {
                        System.out.println(imageFormSiji.getHistogram().get(i).getRgb() + " = "
                                + imageFormSiji.getHistogram().get(i).getJumlah() + " = "
                                + imageFormSiji.getHistogram().get(i).getJumlahKumulatif() + " = "
                                + imageFormSiji.getHistogram().get(i).getHasilEkualisasi());
                        jumlah += imageFormSiji.getHistogram().get(i).getJumlah();
                        chartBarAwal.setValue(imageFormSiji.getHistogram().get(i).getJumlah(), "aha",
                                "" + imageFormSiji.getHistogram().get(i).getRgb());
                        chartBarHasil.setValue(imageFormSiji.getHistogram().get(i).getHasilEkualisasi(), "aha",
                                "" + imageFormSiji.getHistogram().get(i).getRgb());
                    }

                    JFreeChart chartSiji = ChartFactory.createBarChart("Histogam Citra Awal", "RGB", "Jumlah",
                            chartBarAwal, PlotOrientation.VERTICAL, false, true, false);
                    JFreeChart chartLoro = ChartFactory.createBarChart("Histogram Citra Ekualisasi", "RGB",
                            "Jumlah", chartBarHasil, PlotOrientation.VERTICAL, false, true, false);
                    CategoryPlot categoryPlotSiji = chartSiji.getCategoryPlot();
                    CategoryPlot categoryPlotLoro = chartLoro.getCategoryPlot();
                    categoryPlotSiji.setRangeGridlinePaint(Color.orange);
                    categoryPlotLoro.setRangeGridlinePaint(Color.orange);

                    ChartPanel cpanelSiji = new ChartPanel(chartSiji);
                    ChartPanel cpanelLoro = new ChartPanel(chartLoro);
                    chartAwal.removeAll();
                    chartAwal.add(cpanelSiji);
                    chartAwal.validate();

                    chartEkualisasi.removeAll();
                    chartEkualisasi.add(cpanelLoro);
                    chartEkualisasi.validate();

                    System.out.println("Jumlah = " + jumlah);
                    citraLabel.setText("");
                    citraGrayLabel.setText("");
                    citraEkualisasi.setText("");
                    citraLabel.setIcon(new ImageIcon(bimg.getScaledInstance(230, 230, 0)));
                    //resetCitra();
                    ukuranCitra.setText("Ukuran Citra : " + imageFormSiji.getTinggi() + " x "
                            + imageFormSiji.getLebar() + "");
                    imageFormSiji.setSmoothingImage();
                    imageFormSiji.setSharpeningImage();
                    citraEkualisasi.setIcon(
                            new ImageIcon(imageFormSiji.getEqualImage().getScaledInstance(230, 230, 0)));
                    citraGrayLabel.setIcon(
                            new ImageIcon(imageFormSiji.getGrayImage().getScaledInstance(230, 230, 0)));
                    citraSmoothingHasil.setIcon(new ImageIcon(imageFormSiji.getSmoothingImage()));
                    citraSharpheningHasil.setIcon(new ImageIcon(imageFormSiji.getSharpeningImage()));
                }
            };
            t.start();

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

From source file:library.Form_Library.java

License:asdf

public static Icon loadImage(String linkImage, int k,
        int m) {/*linkImage l tn icon, k kch thc chi?u rng mnh mun,m chi?u di v hm ny tr v? gi tr l 1 icon.*/
    try {//from  w  w w.  java2  s .  co m
        BufferedImage image = ImageIO.read(new File(linkImage));//?c nh dng BufferedImage

        int x = k;
        int y = m;
        int ix = image.getWidth();
        int iy = image.getHeight();
        int dx = 0, dy = 0;

        if (x / y > ix / iy) {
            dy = y;
            dx = dy * ix / iy;
        } else {
            dx = x;
            dy = dx * iy / ix;
        }

        return new ImageIcon(image.getScaledInstance(dx, dy, image.SCALE_SMOOTH));

    } catch (IOException e) {
        //            System.out.println("Err: " + e.getMessage());
    }
    return null;
}

From source file:ucar.unidata.idv.ui.ImageGenerator.java

/**
 * Resize the image/*  w w w .ja v a2  s  .  co m*/
 *
 * @param image The image
 * @param widthStr width of desired image (pixels)
 * @param heightStr height of desired image (pixels)
 *
 * @return The resized image
 */
public BufferedImage resizeImage(BufferedImage image, String widthStr, String heightStr) {
    int imageWidth = image.getWidth(null);
    int imageHeight = image.getHeight(null);
    int width = -1;
    int height = -1;
    if (!widthStr.equals("-1")) {
        width = (int) toDouble(widthStr, imageWidth);
    }
    if (!heightStr.equals("-1")) {
        height = (int) toDouble(heightStr, imageHeight);
    }
    if ((width == -1) && (height == -1)) {
        return image;
    }

    BufferedImage resizedImage = ImageUtils.toBufferedImage(
            image.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING), BufferedImage.TYPE_INT_RGB);
    return resizedImage;

}