Example usage for java.awt Image SCALE_DEFAULT

List of usage examples for java.awt Image SCALE_DEFAULT

Introduction

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

Prototype

int SCALE_DEFAULT

To view the source code for java.awt Image SCALE_DEFAULT.

Click Source Link

Document

Use the default image-scaling algorithm.

Usage

From source file:application.Main.java

public void createTrayIcon(final Stage stage) {
    // if the operating system
    // supports the system tray
    if (SystemTray.isSupported()) {
        // get the SystemTray instance
        SystemTray tray = SystemTray.getSystemTray();
        // load an image
        java.awt.Image image = null;
        try {/*  w  w w.  j  a va 2  s . c o  m*/
            //                File file = new File(iconLocation);
            //                image = ImageIO.read(file);
            URL urlIcon = Main.class.getResource(iconLocation);
            image = ImageIO.read(urlIcon);
        } catch (IOException ex) {
            System.out.println(ex);
        }

        stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent t) {
                hide(stage);
            }
        });

        // create an action listener to listen for default action executed on the tray icon
        final ActionListener closeListener = new ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent e) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        stage.close();
                        controller.terminate();
                        //                           // fileWatcher.setTerminateWatching(Boolean.TRUE);
                        System.out.println(applicationTitle + " terminated!");
                        Platform.exit();
                        System.exit(0);
                    }
                });
            }
        };

        ActionListener showListener = new ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent e) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        stage.show();
                    }
                });
            }
        };

        // create a pop-up menu
        PopupMenu popupMenu = new PopupMenu();

        MenuItem nameItem = new MenuItem(applicationTitle);
        nameItem.addActionListener(showListener);
        popupMenu.add(nameItem);

        popupMenu.addSeparator();

        MenuItem showItem = new MenuItem("Show");
        showItem.addActionListener(showListener);
        popupMenu.add(showItem);

        MenuItem closeItem = new MenuItem("Close");
        closeItem.addActionListener(closeListener);
        popupMenu.add(closeItem);

        /// ... add other menu items

        // construct a TrayIcon, scaling the image to 16x16 (the default dimensions of a tray icon)
        trayIcon = new TrayIcon(image.getScaledInstance(24, 24, Image.SCALE_DEFAULT), applicationTitle,
                popupMenu);
        // set the TrayIcon properties
        trayIcon.addActionListener(showListener);

        // add the tray image
        try {
            tray.add(trayIcon);
        } catch (AWTException e) {
            System.err.println(e);
        }
    }
}

From source file:com.akman.excel.view.frmSelectImage.java

private void btnSelectImageActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnSelectImageActionPerformed
{//GEN-HEADEREND:event_btnSelectImageActionPerformed
    JFileChooser chooser = new JFileChooser();

    FileNameExtensionFilter filter = new FileNameExtensionFilter("Image files", "jpg", "png", "gif", "bmp");
    chooser.setFileFilter(filter);//from  w ww . j a  v a2 s.c o  m

    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setDialogTitle("Select The Image");
    chooser.setMultiSelectionEnabled(false);
    int res = chooser.showOpenDialog(null);
    if (res == JFileChooser.APPROVE_OPTION) {

        //Saving file inside the file
        File file = chooser.getSelectedFile();

        //        if(!file.equals(filter))
        //        {
        //        JOptionPane.showMessageDialog(null, "Wrong File Selected","ERROR",JOptionPane.ERROR_MESSAGE);
        //        return;
        //        }

        //System.out.println(file.getAbsolutePath());
        ImageIcon image = new ImageIcon(file.getAbsolutePath());

        fileName = file.getAbsolutePath();

        // Get Width And Height of PicLabel
        Rectangle rect = lblImage.getBounds();

        //System.out.println(lblImage.getBounds());
        //Scaling the image to fit in the picLabel
        Image scaledimage = image.getImage().getScaledInstance(rect.width, rect.height, Image.SCALE_DEFAULT);
        //converting the image back to image icon to make an acceptable picLabel
        image = new ImageIcon(scaledimage);

        lblImage.setIcon(image);

        txtPath.setText(fileName);

        try {

            File images = new File(fileName);

            FileInputStream fis = new FileInputStream(images);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            byte[] buf = new byte[1024];

            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum);
            }

            person_image = bos.toByteArray();

        } catch (Exception e) {

            JOptionPane.showMessageDialog(null, e);
        }

    }
}

From source file:org.sbs.util.ImageCompress.java

/**
 * @param originalFile//from w w  w  .  j  a  v  a  2s. c o m
 *            ?
 * @param resizedFile
 *            ??
 * @param width
 *            ?
 * @param height
 *            ? -1?
 * @param format
 *            ? jpg, png, gif(?)
 * @throws IOException
 */
public void resize(File originalFile, File resizedFile, int width, int height, String format)
        throws IOException {
    if (format != null && "gif".equals(format.toLowerCase())) {
        resize(originalFile, resizedFile, width, height, 1);
        return;
    }
    FileInputStream fis = new FileInputStream(originalFile);
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    int readLength = -1;
    int bufferSize = 1024;
    byte bytes[] = new byte[bufferSize];
    while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) {
        byteStream.write(bytes, 0, readLength);
    }
    byte[] in = byteStream.toByteArray();
    fis.close();
    byteStream.close();

    Image inputImage = Toolkit.getDefaultToolkit().createImage(in);
    waitForImage(inputImage);
    int imageWidth = inputImage.getWidth(null);
    if (imageWidth < 1)
        throw new IllegalArgumentException("image width " + imageWidth + " is out of range");
    int imageHeight = inputImage.getHeight(null);
    if (imageHeight < 1)
        throw new IllegalArgumentException("image height " + imageHeight + " is out of range");

    // Create output image.
    if (height == -1) {
        double scaleW = (double) imageWidth / (double) width;
        double scaleY = (double) imageHeight / (double) height;
        if (scaleW >= 0 && scaleY >= 0) {
            if (scaleW > scaleY) {
                height = -1;
            } else {
                width = -1;
            }
        }
    }
    Image outputImage = inputImage.getScaledInstance(width, height, java.awt.Image.SCALE_DEFAULT);
    checkImage(outputImage);
    encode(new FileOutputStream(resizedFile), outputImage, format);
}

From source file:fr.isen.browser5.Util.UrlLoader.java

public void setTabTitleFavicon() {
    String title = doc.title();//w ww. j av a2  s.com
    title = Str.shortenString(title, 12);
    int tabIndex = tabView.getCurrentTabIndex();
    JPanel tabPanel = (JPanel) tabView.getCurrentFrame().getTabPane().getTabComponentAt(tabIndex);
    JLabel titleLabel = (JLabel) tabPanel.getComponent(0);
    titleLabel.setText(title);

    String baseUrl = pageUrl.getProtocol() + "://" + pageUrl.getHost();
    Element element = doc.head().select("link[href~=.*\\.(ico|png)]").first();
    String favicoUrlStr = "";
    if (element != null) {
        favicoUrlStr = element.attr("abs:href");
    } else {
        element = doc.head().select("meta[itemprop=image]").first();
        if (element != null) {
            favicoUrlStr = baseUrl + element.attr("content");
        }
    }

    ImageIcon icon = null;
    try {
        if (!favicoUrlStr.isEmpty()) {
            if (favicoUrlStr.endsWith(".ico")) {
                java.util.List<BufferedImage> imgs = ICODecoder.read(new URL(favicoUrlStr).openStream());
                icon = new ImageIcon(imgs.get(0));
            } else {
                icon = new ImageIcon(new URL(favicoUrlStr));
            }
            icon = new ImageIcon(icon.getImage().getScaledInstance(16, 16, Image.SCALE_DEFAULT));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    titleLabel.setIcon(icon);

    HistoryEntry historyEntry = new HistoryEntry(title, pageUrl.toString(), Instant.now().getEpochSecond(),
            icon, -1L);
    globalHistoryDAO.create(historyEntry);
}

From source file:FileChooserDemo2.java

public void loadImage() {
    if (file == null) {
        thumbnail = null;//from   w w w.ja  va2  s.  c  o  m
        return;
    }

    // Don't use createImageIcon (which is a wrapper for getResource)
    // because the image we're trying to load is probably not one
    // of this program's own resources.
    ImageIcon tmpIcon = new ImageIcon(file.getPath());
    if (tmpIcon != null) {
        if (tmpIcon.getIconWidth() > 90) {
            thumbnail = new ImageIcon(tmpIcon.getImage().getScaledInstance(90, -1, Image.SCALE_DEFAULT));
        } else { // no need to miniaturize
            thumbnail = tmpIcon;
        }
    }
}

From source file:yt_server_side.YT_Server_Side.java

/**
 * This method goes to a specified webpage, recieves the content and
 * attempts to parse it to an ImageIcon. This will only work if the only
 * content on the page is the img. This is why the url must be derived from
 * the 'src' attribute of an <img> element.
 *
 * @param url The direct url to an image, often gotten from the 'src'
 * attribute in an <img> element.//  w w  w.j  ava  2s .  c o  m
 * @return an ImageIcon from the give url.
 */
private ImageIcon urlToJpg(String url) {
    ImageIcon bi;
    System.out.println("Attempting to convert " + url + " to jpg...");
    try {
        System.out.println("Reading WebResponse...");
        WebClient wc = new WebClient();
        WebResponse wr = wc.getPage(url).getWebResponse();
        System.out.println("\tWebResponse read " + " @ " + System.currentTimeMillis() + "...");
        byte[] webResponseData = new byte[2000000]; // buffer for images up to 2mb in size

        wr.getContentAsStream().read(webResponseData);
        System.out
                .println("\t\tWebResponseData filled with data " + " @ " + System.currentTimeMillis() + "...");

        bi = new ImageIcon(
                new ImageIcon(webResponseData).getImage().getScaledInstance(120, 80, Image.SCALE_DEFAULT));
        System.out.println("\t\t\tbi intialized...");
    } catch (IOException | FailingHttpStatusCodeException ex) {
        System.out.println("IO Exception has been thrown when retrieving an image from " + url + ".");
        System.out.println("\tAttempting to retrieve default background image...");
        bi = new ImageIcon(getClass().getResource("/graphics/TGJ_Logo_Medium.png"));
        System.out.println("Default background image initialized.");
    }
    System.out.println("Returning bi.");
    return (bi);
}

From source file:org.tsho.dmc2.core.chart.LyapunovRenderer.java

public boolean renderArea(Graphics2D g2, Rectangle2D dataArea) {

    g2.setPaint(plot.paint);//from www .j a v  a2s .c om

    if (pass == 1) {
        if (image != null) {
            double x = dataArea.getX();
            double y = dataArea.getY();
            //there is a problem when using Graphics2D with affine transform 
            //and BufferedImage; using subclass of Image returned below.
            //rescaling needed because adding legend causes dataArea to change.
            Image scaledImage = image.getScaledInstance((int) dataArea.getWidth() - 1,
                    (int) dataArea.getHeight() - 1, Image.SCALE_DEFAULT);
            g2.drawImage(scaledImage, (int) x + 1, (int) y + 1, (int) dataArea.getWidth() - 1,
                    (int) dataArea.getHeight() - 1, this);
            //g2.translate(-1,-1);
            //g2.drawRect((int) x, (int) y, (int) dataArea.getWidth(),(int) dataArea.getHeight());
            //g2.translate(1,1);
        }
        return true;
    }

    final double parHStep, parVStep;
    double parHLower = plot.getDomainAxis().getRange().getLowerBound();
    double parHUpper = plot.getDomainAxis().getRange().getUpperBound();
    double parVLower = plot.getRangeAxis().getRange().getLowerBound();
    double parVUpper = plot.getRangeAxis().getRange().getUpperBound();

    parHStep = Math.abs(parHUpper - parHLower) / dataArea.getWidth();
    parVStep = Math.abs(parVUpper - parVLower) / dataArea.getHeight();

    image = new BufferedImage((int) dataArea.getWidth(), (int) dataArea.getHeight(),
            BufferedImage.TYPE_INT_RGB);
    WritableRaster raster = image.getRaster();
    DataBufferInt dataBuffer = (DataBufferInt) raster.getDataBuffer();
    int[] data = dataBuffer.getData();

    final double parHStart = parHLower + parHStep / 2;
    final double parVStart = parVUpper - parVStep / 2;

    if (model instanceof ODE) {
        double step = stepSize; // stepSize and timeStep probably mean the same thing, one for discrete another for ODE
        double[] result = new double[model.getNVar()];

        for (int i = 0; i < (int) dataArea.getWidth(); i++) {
            for (int j = 0; j < (int) dataArea.getHeight(); j++) {

                parameters.put(firstParLabel, parHStart + i * parHStep);
                parameters.put(secondParLabel, parVStart - j * parVStep);

                int color;
                result = Lua.evaluateLyapunovExponentsODE(model, parameters, initialPoint, timePeriod,
                        stepSize);

                if (result == null) {
                    System.out.println("i: " + i + " j: " + j);
                    System.out.println("par1: " + parHStart + i * parHStep);
                    System.out.println("par2: " + parVStart + j * parVStep);
                    g2.drawImage(image, null, (int) dataArea.getX() + 1, (int) dataArea.getY() + 1);
                    return false;
                }

                int zer = 0;
                int pos = 0;
                int neg = 0;
                int nan = 0;
                for (int ii = 0; ii < result.length; ii++) {
                    if (Math.abs(result[ii]) == (1.0 / 0.0))
                        nan++;
                    else if (Math.abs(result[ii]) <= epsilon)
                        zer++;
                    else if (result[ii] > epsilon)
                        pos++;
                    else if (result[ii] < (-epsilon))
                        neg++;
                    else
                        nan++;
                }

                color = (lyapunovColors.getColor(zer, pos, neg, nan)).getRGB();
                ExpsSigns es = new ExpsSigns(zer, pos, neg, nan);
                if (!signsSet.contains(es))
                    signsSet.add(es);

                data[i + j * (int) dataArea.getWidth()] = color;

                if (stopped == true)
                    return false;

                if (j == (int) dataArea.getHeight() - 1) {
                    g2.drawImage(image, null, (int) dataArea.getX() + 1, (int) dataArea.getY() + 1);
                }
            } //end for
        } //end for
    } //end if ODE
    else {
        for (int i = 0; i < (int) dataArea.getWidth(); i++) {
            for (int j = 0; j < (int) dataArea.getHeight(); j++) {

                parameters.put(firstParLabel, parHStart + i * parHStep);
                parameters.put(secondParLabel, parVStart - j * parVStep);

                double[] result;
                int color;

                result = Lua.evaluateLyapunovExponents(model, parameters, initialPoint, iterations);

                if (result == null) {
                    System.out.println("i: " + i + " j: " + j);
                    System.out.println("par1: " + parHStart + i * parHStep);
                    System.out.println("par2: " + parVStart + j * parVStep);
                    g2.drawImage(image, null, (int) dataArea.getX() + 1, (int) dataArea.getY() + 1);
                    return false;
                }

                int zer = 0;
                int pos = 0;
                int neg = 0;
                int nan = 0;
                for (int ii = 0; ii < result.length; ii++) {
                    if (Math.abs(result[ii]) == (1.0 / 0.0))
                        nan++;
                    else if (Math.abs(result[ii]) <= epsilon)
                        zer++;
                    else if (result[ii] > epsilon)
                        pos++;
                    else if (result[ii] < (-epsilon))
                        neg++;
                    else
                        nan++;
                }

                color = (lyapunovColors.getColor(zer, pos, neg, nan)).getRGB();
                ExpsSigns es = new ExpsSigns(zer, pos, neg, nan);
                if (!signsSet.contains(es))
                    signsSet.add(es);

                data[i + j * (int) dataArea.getWidth()] = color;

                if (stopped == true)
                    return false;

                if (j == (int) dataArea.getHeight() - 1)
                    g2.drawImage(image, null, (int) dataArea.getX() + 1, (int) dataArea.getY() + 1);
            } //end for
        } //end for
    } //end else
    return true;
}

From source file:generadorqr.jifrNuevoQr.java

void CargarImagen(JLabel label, Integer identificador) {
    int resultado;
    // ventana = new CargarFoto();
    JFileChooser jfchCargarfoto = new JFileChooser();
    FileNameExtensionFilter filtro = new FileNameExtensionFilter("JPG", "jpg");
    jfchCargarfoto.setFileFilter(filtro);
    resultado = jfchCargarfoto.showOpenDialog(null);
    if (JFileChooser.APPROVE_OPTION == resultado) {
        fichero = jfchCargarfoto.getSelectedFile();
        try {/*  w  w  w.  j a v a2s  . co m*/
            tempImagen[identificador] = fichero.getPath();
            tempNombreArchivo[identificador] = fichero.getName();
            ImageIcon icon = new ImageIcon(fichero.toString());
            Icon icono = new ImageIcon(icon.getImage().getScaledInstance(label.getWidth(), label.getHeight(),
                    Image.SCALE_DEFAULT));
            label.setText(null);
            label.setIcon(icono);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error abriendo la imagen" + ex);
        }
    }
}

From source file:com.akman.excel.view.frmExportExcel.java

private void btnSelectImageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectImageActionPerformed
    JFileChooser chooser = new JFileChooser();

    FileNameExtensionFilter filter = new FileNameExtensionFilter("Image files", "jpg", "png", "gif", "bmp");
    chooser.setFileFilter(filter);/*from ww  w  .  j a va  2 s  .com*/

    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setDialogTitle("Select The Image");
    chooser.setMultiSelectionEnabled(false);
    int res = chooser.showOpenDialog(null);
    if (res == JFileChooser.APPROVE_OPTION) {

        //Saving file inside the file
        File file = chooser.getSelectedFile();

        //        if(!file.equals(filter))
        //        {
        //        JOptionPane.showMessageDialog(null, "Wrong File Selected","ERROR",JOptionPane.ERROR_MESSAGE);
        //        return;
        //        }
        //System.out.println(file.getAbsolutePath());
        ImageIcon image = new ImageIcon(file.getAbsolutePath());

        fileNameSignature = file.getAbsolutePath();

        // Get Width And Height of PicLabel
        Rectangle rect = lblImage.getBounds();

        //System.out.println(lblImage.getBounds());
        //Scaling the image to fit in the picLabel
        Image scaledimage = image.getImage().getScaledInstance(rect.width, rect.height, Image.SCALE_DEFAULT);
        //converting the image back to image icon to make an acceptable picLabel
        image = new ImageIcon(scaledimage);

        lblImage.setIcon(image);

        txtPathSig.setText(fileNameSignature);

        try {

            File images = new File(fileNameSignature);

            FileInputStream fis = new FileInputStream(images);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            byte[] buf = new byte[1024];

            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum);
            }

            person_image = bos.toByteArray();

        } catch (Exception e) {

            JOptionPane.showMessageDialog(null, e);
        }

    }
}

From source file:com.biosis.biosislite.vistas.inventario.MantenimientoFactura.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    // TODO add your handling code here:
    JFileChooser fc = new JFileChooser();
    int respuesta = fc.showOpenDialog(this);
    if (respuesta == JFileChooser.APPROVE_OPTION) {
        File archivoElegido = fc.getSelectedFile();
        facturaField.setText(archivoElegido.getAbsolutePath());

        //            fotolbl.setIcon(new ImageIcon("C:/Users/Documentos/Desktop/HS/" + fotosField.getText()));
        ImageIcon fot = new ImageIcon(facturaField.getText());
        Icon icono = new ImageIcon(fot.getImage().getScaledInstance(lblFactura.getWidth(),
                lblFactura.getHeight(), Image.SCALE_DEFAULT));
        lblFactura.setIcon(icono);/*  www.j  ava 2s .  c  o  m*/

    }
}