Example usage for java.awt MediaTracker addImage

List of usage examples for java.awt MediaTracker addImage

Introduction

In this page you can find the example usage for java.awt MediaTracker addImage.

Prototype

public void addImage(Image image, int id) 

Source Link

Document

Adds an image to the list of images being tracked by this media tracker.

Usage

From source file:de.cenote.jasperstarter.Report.java

private Map<String, Object> getCmdLineReportParams() {
    JRParameter[] jrParameterArray = jasperReport.getParameters();
    Map<String, JRParameter> jrParameters = new HashMap<String, JRParameter>();
    Map<String, Object> parameters = new HashMap<String, Object>();
    List<String> params;
    if (config.hasParams()) {
        params = config.getParams();//from ww w.j  a v a 2s  .co m
        for (JRParameter rp : jrParameterArray) {
            jrParameters.put(rp.getName(), rp);
        }
        String paramName = null;
        //String paramType = null;
        String paramValue = null;

        for (String p : params) {
            try {
                paramName = p.split("=")[0];
                paramValue = p.split("=", 2)[1];
                if (config.isVerbose()) {
                    System.out.println("Using report parameter: " + paramName + " = " + paramValue);
                }
            } catch (Exception e) {
                throw new IllegalArgumentException("Wrong report param format! " + p, e);
            }
            if (!jrParameters.containsKey(paramName)) {
                throw new IllegalArgumentException("Parameter '" + paramName + "' does not exist in report!");
            }

            JRParameter reportParam = jrParameters.get(paramName);

            try {
                // special parameter handlers must also implemeted in
                // ParameterPanel.java
                if (Date.class.equals(reportParam.getValueClass())) {
                    // Date must be in ISO8601 format. Example 2012-12-31
                    DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd");
                    parameters.put(paramName, (Date) dateFormat.parse(paramValue));
                } else if (Image.class.equals(reportParam.getValueClass())) {
                    Image image = Toolkit.getDefaultToolkit()
                            .createImage(JRLoader.loadBytes(new File(paramValue)));
                    MediaTracker traker = new MediaTracker(new Panel());
                    traker.addImage(image, 0);
                    try {
                        traker.waitForID(0);
                    } catch (Exception e) {
                        throw new IllegalArgumentException("Image tracker error: " + e.getMessage(), e);
                    }
                    parameters.put(paramName, image);
                } else if (Locale.class.equals(reportParam.getValueClass())) {
                    parameters.put(paramName, LocaleUtils.toLocale(paramValue));
                } else {
                    // handle generic parameters with string constructor
                    try {
                        parameters.put(paramName, reportParam.getValueClass().getConstructor(String.class)
                                .newInstance(paramValue));
                    } catch (InstantiationException ex) {
                        throw new IllegalArgumentException("Parameter '" + paramName + "' of type '"
                                + reportParam.getValueClass().getName() + " caused " + ex.getClass().getName()
                                + " " + ex.getMessage(), ex);
                    } catch (IllegalAccessException ex) {
                        throw new IllegalArgumentException("Parameter '" + paramName + "' of type '"
                                + reportParam.getValueClass().getName() + " caused " + ex.getClass().getName()
                                + " " + ex.getMessage(), ex);
                    } catch (InvocationTargetException ex) {
                        Throwable cause = ex.getCause();
                        throw new IllegalArgumentException("Parameter '" + paramName + "' of type '"
                                + reportParam.getValueClass().getName() + " caused "
                                + cause.getClass().getName() + " " + cause.getMessage(), cause);
                    } catch (NoSuchMethodException ex) {
                        throw new IllegalArgumentException("Parameter '" + paramName + "' of type '"
                                + reportParam.getValueClass().getName() + " with value '" + paramValue
                                + "' is not supported by JasperStarter!", ex);
                    }
                }
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException(
                        "NumberFormatException: " + e.getMessage() + "\" in \"" + p + "\"", e);
            } catch (java.text.ParseException e) {
                throw new IllegalArgumentException(e.getMessage() + "\" in \"" + p + "\"", e);
            } catch (JRException e) {
                throw new IllegalArgumentException("Unable to load image from: " + paramValue, e);
            }
        }
    }
    return parameters;
}

From source file:Jpeg.java

public JpegEncoder(Image image, int quality, OutputStream out) {
    MediaTracker tracker = new MediaTracker(this);
    tracker.addImage(image, 0);
    try {/*  ww w .  j  a va2 s  .com*/
        tracker.waitForID(0);
    } catch (InterruptedException e) {
        // Got to do something?
    }
    /*
     * Quality of the image. 0 to 100 and from bad image quality, high
     * compression to good image quality low compression
     */
    Quality = quality;

    /*
     * Getting picture information It takes the Width, Height and RGB scans of
     * the image.
     */
    JpegObj = new JpegInfo(image);

    imageHeight = JpegObj.imageHeight;
    imageWidth = JpegObj.imageWidth;
    outStream = new BufferedOutputStream(out);
    dct = new DCT(Quality);
    Huf = new Huffman(imageWidth, imageHeight);
}

From source file:net.sradonia.gui.SplashScreen.java

/**
 * Creates a new splash screen.//from   w  ww  .java2  s  .  c  om
 * 
 * @param image
 *            the image to display
 * @param title
 *            the title of the window
 */
public SplashScreen(Image image, String title) {
    log.debug("initializing splash screen");

    if (image == null)
        throw new IllegalArgumentException("null image");

    // create the frame
    window = new JFrame(title) {
        private static final long serialVersionUID = 2193620921531262633L;

        @Override
        public void paint(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            g2d.drawImage(splash, 0, 0, this);
        }
    };
    window.setUndecorated(true);

    // wait for the image to load
    MediaTracker mt = new MediaTracker(window);
    mt.addImage(image, 0);
    try {
        mt.waitForID(0);
    } catch (InterruptedException e1) {
        log.debug("interrupted while waiting for image loading");
    }

    // check for loading errors
    if (mt.isErrorID(0))
        throw new IllegalArgumentException("couldn't load the image");
    if (image.getHeight(null) <= 0 || image.getWidth(null) <= 0)
        throw new IllegalArgumentException("illegal image size");

    setImage(image);

    window.addWindowFocusListener(new WindowFocusListener() {
        public void windowGainedFocus(WindowEvent e) {
            updateSplash();
        }

        public void windowLostFocus(WindowEvent e) {
        }
    });

    timer = new SimpleTimer(new Runnable() {
        public void run() {
            log.debug(timer.getDelay() + "ms timeout reached");
            timer.setRunning(false);
            setVisible(false);
        }
    }, 5000, false);
    timeoutActive = false;
}

From source file:net.yacy.cora.util.Html2Image.java

/**
 * convert a pdf (first page) to an image. proper values are i.e. width = 1024, height = 1024, density = 300, quality = 75
 * using internal pdf library or external command line tool on linux or mac
 * @param pdf input pdf file/*from  ww w.j  ava  2  s .c o m*/
 * @param image output jpg file
 * @param width
 * @param height
 * @param density (dpi)
 * @param quality
 * @return
 */
public static boolean pdf2image(File pdf, File image, int width, int height, int density, int quality) {
    final File convert = convertMac1.exists() ? convertMac1
            : convertMac2.exists() ? convertMac2 : convertDebian;

    // convert pdf to jpg using internal pdfbox capability
    if (OS.isWindows || !convert.exists()) {
        try {
            PDDocument pdoc = PDDocument.load(pdf);
            BufferedImage bi = new PDFRenderer(pdoc).renderImageWithDPI(0, density, ImageType.RGB);

            return ImageIO.write(bi, "jpg", image);

        } catch (IOException ex) {
        }
    }

    // convert on mac or linux using external command line utility
    try {
        // i.e. convert -density 300 -trim yacy.pdf[0] -trim -resize 1024x -crop x1024+0+0 -quality 75% yacy-convert-300.jpg
        // note: both -trim are necessary, otherwise it is trimmed only on one side. The [0] selects the first page of the pdf
        String command = convert.getAbsolutePath() + " -density " + density + " -trim " + pdf.getAbsolutePath()
                + "[0] -trim -resize " + width + "x -crop x" + height + "+0+0 -quality " + quality + "% "
                + image.getAbsolutePath();
        List<String> message = OS.execSynchronous(command);
        if (image.exists())
            return true;
        ConcurrentLog.warn("Html2Image", "failed to create image with command: " + command);
        for (String m : message)
            ConcurrentLog.warn("Html2Image", ">> " + m);

        // another try for mac: use Image Events using AppleScript in osacript commands...
        // the following command overwrites a pdf with an png, so we must make a copy first
        if (!OS.isMacArchitecture)
            return false;
        File pngFile = new File(pdf.getAbsolutePath() + ".tmp.pdf");
        org.apache.commons.io.FileUtils.copyFile(pdf, pngFile);
        String[] commandx = { "osascript", "-e", "set ImgFile to \"" + pngFile.getAbsolutePath() + "\"", "-e",
                "tell application \"Image Events\"", "-e", "set Img to open file ImgFile", "-e",
                "save Img as PNG", "-e", "end tell" };
        //ConcurrentLog.warn("Html2Image", "failed to create image with command: " + commandx);
        message = OS.execSynchronous(commandx);
        for (String m : message)
            ConcurrentLog.warn("Html2Image", ">> " + m);
        // now we must read and convert this file to a jpg with the target size 1024x1024
        try {
            File newPngFile = new File(pngFile.getAbsolutePath() + ".png");
            pngFile.renameTo(newPngFile);
            Image img = ImageParser.parse(pngFile.getAbsolutePath(), FileUtils.read(newPngFile));
            final Image scaled = img.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
            final MediaTracker mediaTracker = new MediaTracker(new Container());
            mediaTracker.addImage(scaled, 0);
            try {
                mediaTracker.waitForID(0);
            } catch (final InterruptedException e) {
            }
            // finally write the image
            final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            bi.createGraphics().drawImage(scaled, 0, 0, width, height, null);
            ImageIO.write(bi, "jpg", image);
            newPngFile.delete();
            return image.exists();
        } catch (IOException e) {
            ConcurrentLog.logException(e);
            return false;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

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

/**
 * This method initializes the design of the frame.
 *
 *//*  w  ww .  j a  v  a 2  s  .  c  o m*/
private void initialize() {
    GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
    Rectangle bounds = graphicsEnvironment.getMaximumWindowBounds();
    setPreferredSize(bounds.getSize());

    this.setJMenuBar(getBanner());

    this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

    // Sets the main menu (the one separated by jsplitPane1)
    this.setContentPane(getBasePanel());
    this.setTitle(Messages.getString("EditorFrame.application.title")); //$NON-NLS-1$
    addWindowListener(this.windowListener);
    try {
        // Associates the icon (frame.icon = icon_tangara.png) to Tangara
        URL url = EditorFrame.class.getResource(ICON_PATH);
        MediaTracker attenteChargement = new MediaTracker(this);
        Image image = Toolkit.getDefaultToolkit().getImage(url);
        attenteChargement.addImage(image, 0);
        attenteChargement.waitForAll();
        setIconImage(image);
    } catch (InterruptedException e) {
        LOG.warn("Error while loading icon"); //$NON-NLS-1$
    }
    // fileChooser allows to easily choose a file
    // when you open (FILE->OPEN...) you have the choice between .txt or
    // .tgr
    fileChooser = new JFileChooser(Program.instance().getCurrentDirectory());

    // for TangaraFile ".tgr"
    fileChooser.addChoosableFileFilter(new FileFilter() {
        @Override
        public boolean accept(File f) {
            if (f.isDirectory())
                return true;
            return FileUtils.isTangaraFile(f);
        }

        @Override
        public String getDescription() {
            return Messages.getString("EditorFrame.file.programFilesDescription"); //$NON-NLS-1$
        }
    });

    fileChooserWithoutFilter = new JFileChooser(Program.instance().getCurrentDirectory());
    pack();
    setVisible(true);
    setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
}

From source file:org.muse.mneme.impl.AttachmentServiceImpl.java

/**
 * Create a thumbnail image from the full image in the byte[], of the desired width and height and quality, preserving aspect ratio.
 * /*www.j  a v  a2 s.  c om*/
 * @param full
 *        The full image bytes.
 * @param width
 *        The desired max width (pixels).
 * @param height
 *        The desired max height (pixels).
 * @param quality
 *        The JPEG quality (0 - 1).
 * @return The thumbnail JPEG as a byte[].
 * @throws IOException
 * @throws InterruptedException
 */
protected byte[] makeThumb(byte[] full, int width, int height, float quality)
        throws IOException, InterruptedException {
    // read the image from the byte array, waiting till it's processed
    Image fullImage = Toolkit.getDefaultToolkit().createImage(full);
    MediaTracker tracker = new MediaTracker(new Container());
    tracker.addImage(fullImage, 0);
    tracker.waitForID(0);

    // get the full image dimensions
    int fullWidth = fullImage.getWidth(null);
    int fullHeight = fullImage.getHeight(null);

    // preserve the aspect of the full image, not exceeding the thumb dimensions
    if (fullWidth > fullHeight) {
        // full width will take the full desired width, set the appropriate height
        height = (int) ((((float) width) / ((float) fullWidth)) * ((float) fullHeight));
    } else {
        // full height will take the full desired height, set the appropriate width
        width = (int) ((((float) height) / ((float) fullHeight)) * ((float) fullWidth));
    }

    // draw the scaled thumb
    BufferedImage thumbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2D = thumbImage.createGraphics();
    g2D.drawImage(fullImage, 0, 0, width, height, null);

    // encode as jpeg to a byte array
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    BufferedOutputStream out = new BufferedOutputStream(byteStream);
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
    param.setQuality(quality, false);
    encoder.setJPEGEncodeParam(param);
    encoder.encode(thumbImage);
    out.close();
    byte[] thumb = byteStream.toByteArray();

    return thumb;
}

From source file:org.ohdsi.whiteRabbit.WhiteRabbitMain.java

private Image loadIcon(String name, JFrame f) {
    Image icon = Toolkit.getDefaultToolkit().getImage(WhiteRabbitMain.class.getResource(name));
    MediaTracker mediaTracker = new MediaTracker(f);
    mediaTracker.addImage(icon, 0);
    try {/*from www.ja v  a 2  s . com*/
        mediaTracker.waitForID(0);
        return icon;
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    return null;
}

From source file:org.pegadi.client.LoginDialog.java

private void jbInit() {
    Locale.setDefault(new Locale("no", "NO"));
    this.setTitle(str.getString("title"));
    this.addWindowListener(new java.awt.event.WindowAdapter() {
        public void windowOpened(WindowEvent e) {
            this_windowOpened(e);
        }//from w ww  .  j  av  a2  s.  co  m
    });
    loginLabel.setText(str.getString("login"));

    userNameLabel.setText(str.getString("username"));
    okButton.setText("OK");
    okButton.addActionListener(new java.awt.event.ActionListener() {

        public void actionPerformed(ActionEvent e) {
            okButton_actionPerformed(e);
        }
    });
    quitButton.setText(str.getString("quit"));
    quitButton.addActionListener(new java.awt.event.ActionListener() {

        public void actionPerformed(ActionEvent e) {
            quitButton_actionPerformed(e);
        }
    });
    userNameField.setColumns(10);
    userNameField.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyReleased(KeyEvent e) {
            userNameField_keyReleased(e);
        }
    });

    passwordLabel.setText(str.getString("password"));
    passwordField.setColumns(10);
    passwordField.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyReleased(KeyEvent e) {
            passwordField_keyReleased(e);
        }
    });

    serverLabel.setText(str.getString("server"));
    Set keyset = servers.keySet();
    for (Object aKeyset : keyset) {
        String serverKey = (String) aKeyset;
        serverChooser.addItem(serverKey);
    }
    serverChooser.setEnabled(false);

    // gui starts

    JPanel mainPanel = new JPanel();
    this.getContentPane().add(mainPanel);
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

    JPanel labelPanel = new JPanel();
    loginLabel.setFont(new Font(null, Font.PLAIN, 20));

    // add icon
    URL iu = getClass().getResource("/images/pegadi_icon.png");
    Image icon = Toolkit.getDefaultToolkit().getImage(iu);
    MediaTracker mt = new MediaTracker(this);
    mt.addImage(icon, 0);
    try {
        mt.waitForID(0);
    } catch (InterruptedException ie) {
        icon = null;
    }

    if (icon != null) {
        loginLabel.setIcon(new ImageIcon(icon));
        loginLabel.setVerticalTextPosition(JLabel.BOTTOM);
        loginLabel.setHorizontalTextPosition(JLabel.CENTER);
    }

    labelPanel.add(loginLabel);
    labelPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    mainPanel.add(labelPanel);

    JPanel fieldPanel = new JPanel(new SpringLayout());
    fieldPanel.add(userNameLabel);
    fieldPanel.add(userNameField);
    fieldPanel.add(passwordLabel);
    fieldPanel.add(passwordField);
    fieldPanel.add(serverLabel);
    fieldPanel.add(serverChooser);
    SpringUtilities.makeCompactGrid(fieldPanel, 3, 2, //rows, cols
            5, 5, //initialX, initialY
            10, 5);//xPad, yPad
    mainPanel.add(fieldPanel);

    JPanel buttonPanel = new JPanel();
    JPanel buttonWrapperPanel = new JPanel();
    buttonPanel.setLayout(new BorderLayout());
    buttonWrapperPanel.add(okButton);
    buttonWrapperPanel.add(quitButton);
    buttonPanel.add(buttonWrapperPanel, BorderLayout.CENTER);
    buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    mainPanel.add(buttonPanel);
}

From source file:org.pmedv.core.app.SplashScreen.java

/**
 * Show the splash screen.//  w  ww. j  av a  2 s  .c  o  m
 */
public void splash() {

    window = new JWindow();
    // TODO : What was this for?
    // AWTUtilities.setWindowOpaque(window, false);

    if (image == null) {
        image = loadImage(imageResourcePath);
        if (image == null) {
            return;
        }
    }

    MediaTracker mediaTracker = new MediaTracker(window);
    mediaTracker.addImage(image, 0);

    try {
        mediaTracker.waitForID(0);
    } catch (InterruptedException e) {
        log.error("Interrupted while waiting for splash image to load.");
    }

    int width = image.getWidth(null);
    int height = image.getHeight(null);

    BufferedImage bimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g2d = (Graphics2D) bimg.createGraphics();

    g2d.drawImage(image, 0, 0, null);
    g2d.setColor(Color.BLACK);
    g2d.setFont(new Font("Arial", Font.BOLD, 10));
    InputStream is = getClass().getClassLoader().getResourceAsStream("application.properties");
    Properties properties = new Properties();
    try {
        properties.load(is);
    } catch (IOException e1) {
        properties.setProperty("version", "not set");
    }

    String version = properties.getProperty("version");

    File f = new File("build.number");

    properties = new Properties();

    try {
        properties.load(new FileReader(f));
    } catch (IOException e1) {
        properties.setProperty("build.number", "00");
    }

    String buildNumber = properties.getProperty("build.number");

    g2d.drawString("Version " + version + "." + buildNumber, 400, 305);

    JLabel panelImage = new JLabel(new ImageIcon(bimg));

    window.getContentPane().add(panelImage);
    window.getContentPane().add(progressBar, BorderLayout.SOUTH);
    window.pack();

    WindowUtils.center(window);

    window.setVisible(true);
}