Example usage for java.awt MediaTracker waitForID

List of usage examples for java.awt MediaTracker waitForID

Introduction

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

Prototype

public void waitForID(int id) throws InterruptedException 

Source Link

Document

Starts loading all images tracked by this media tracker with the specified identifier.

Usage

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

/**
 * Creates a new splash screen.//from  w w w .ja  va  2s .c o  m
 * 
 * @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   w w  w.  j av a 2  s  .co 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.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.
 * /*from   ww  w  . j a v a 2s  .co m*/
 * @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);/*  ww  w  .  java2  s.c o m*/
    try {
        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  w  w  .j  a va2s . c  o  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.// www .  j  a va  2s  . c  om
 */
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);
}