Example usage for java.awt MediaTracker MediaTracker

List of usage examples for java.awt MediaTracker MediaTracker

Introduction

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

Prototype

public MediaTracker(Component comp) 

Source Link

Document

Creates a media tracker to track images for a given component.

Usage

From source file:Jpeg.java

public JpegEncoder(Image image, int quality, OutputStream out) {
    MediaTracker tracker = new MediaTracker(this);
    tracker.addImage(image, 0);/*from   w  ww .  j  ava  2s .co  m*/
    try {
        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:com.t3.image.ImageUtil.java

public static Image bytesToImage(byte[] imageBytes) throws IOException {

    if (imageBytes == null) {
        System.out.println("WEhaah??");
    }//from   w  w w  . j  a  v a  2 s.  c  o  m
    Throwable exception = null;
    Image image = null;
    try {
        image = Toolkit.getDefaultToolkit().createImage(imageBytes);
        MediaTracker tracker = new MediaTracker(observer);
        tracker.addImage(image, 0);
        tracker.waitForID(0);
    } catch (Throwable t) {
        exception = t;
    }
    if (image == null || exception != null || image.getWidth(null) <= 0 || image.getHeight(null) <= 0) {
        // Try the newer way (although it pretty much sucks rocks)
        image = ImageIO.read(new ByteArrayInputStream(imageBytes));
    }

    if (image == null) {
        throw new IOException("Could not load image: " + exception);
    }

    return image;
}

From source file:net.rptools.lib.image.ImageUtil.java

/**
 * Converts a byte array into an {@link Image} instance.
 * //from w  w w.  j  a  v  a2s.c om
 * @param imageBytes
 *            bytes to convert
 * @return
 * @throws IOException
 */
public static Image bytesToImage(byte[] imageBytes) throws IOException {
    if (imageBytes == null) {
        throw new IOException("Could not load image - no data provided");
    }
    boolean interrupted = false;
    Throwable exception = null;
    Image image = null;
    image = Toolkit.getDefaultToolkit().createImage(imageBytes);
    MediaTracker tracker = new MediaTracker(observer);
    tracker.addImage(image, 0);
    do {
        try {
            interrupted = false;
            tracker.waitForID(0); // This is the only method that throws an exception
        } catch (InterruptedException t) {
            interrupted = true;
            continue;
        } catch (Throwable t) {
            exception = t;
        }
    } while (interrupted);
    if (image == null || exception != null || image.getWidth(null) <= 0 || image.getHeight(null) <= 0) {
        // Try the newer way (although it pretty much sucks rocks)
        image = ImageIO.read(new ByteArrayInputStream(imageBytes));
    }
    if (image == null) {
        throw new IOException("Could not load image", exception);
    }
    return image;
}

From source file:Animator.java

/**
 * Initialize the applet. Get parameters.
 *///  w  w  w  .ja va 2  s. c  om
public void init() {

    tracker = new MediaTracker(this);

    try {
        String param = getParameter("IMAGESOURCE");
        imageSource = (param == null) ? getDocumentBase() : new URL(getDocumentBase(), param + "/");

        param = getParameter("PAUSE");
        globalPause = (param != null) ? Integer.parseInt(param) : defaultPause;

        param = getParameter("REPEAT");
        repeat = (param == null) ? true : (param.equalsIgnoreCase("yes") || param.equalsIgnoreCase("true"));

        int startImage = 1;
        int endImage = 1;
        param = getParameter("ENDIMAGE");
        if (param != null) {
            endImage = Integer.parseInt(param);
            param = getParameter("STARTIMAGE");
            if (param != null) {
                startImage = Integer.parseInt(param);
            }
            param = getParameter("NAMEPATTERN");
            images = prepareImageRange(startImage, endImage, param);
        } else {
            param = getParameter("STARTIMAGE");
            if (param != null) {
                startImage = Integer.parseInt(param);
                param = getParameter("NAMEPATTERN");
                images = prepareImageRange(startImage, endImage, param);
            } else {
                param = getParameter("IMAGES");
                if (param == null) {
                    showStatus("No legal IMAGES, STARTIMAGE, or ENDIMAGE " + "specified.");
                    return;
                } else {
                    images = parseImages(param);
                }
            }
        }

        param = getParameter("BACKGROUND");
        if (param != null) {
            backgroundImageURL = new URL(imageSource, param);
        }

        param = getParameter("STARTUP");
        if (param != null) {
            startUpImageURL = new URL(imageSource, param);
        }

        param = getParameter("SOUNDSOURCE");
        soundSource = (param == null) ? imageSource : new URL(getDocumentBase(), param + "/");

        param = getParameter("SOUNDS");
        if (param != null) {
            sounds = parseSounds(param, images);
        }

        param = getParameter("PAUSES");
        if (param != null) {
            durations = parseDurations(param, images);
        }

        param = getParameter("POSITIONS");
        if (param != null) {
            positions = parsePositions(param, images);
        }

        param = getParameter("SOUNDTRACK");
        if (param != null) {
            soundtrackURL = new URL(soundSource, param);
        }
    } catch (MalformedURLException e) {
        showParseError(e);
    } catch (ParseException e) {
        showParseError(e);
    }

    setFrameNum(0);
}

From source file:snapshot.java

public static Object respond(final RequestHeader header, serverObjects post, final serverSwitch env) {
    final Switchboard sb = (Switchboard) env;

    final serverObjects defaultResponse = new serverObjects();

    final boolean authenticated = sb.adminAuthenticated(header) >= 2;
    final String ext = header.get(HeaderFramework.CONNECTION_PROP_EXT, "");

    if (ext.isEmpty()) {
        throw new TemplateProcessingException(
                "Missing extension. Try with rss, xml, json, pdf, png or jpg." + ext,
                HttpStatus.SC_BAD_REQUEST);
    }/*  w ww.  j av  a2 s .  c o m*/

    if (ext.equals("rss")) {
        // create a report about the content of the snapshot directory
        if (!authenticated) {
            defaultResponse.authenticationRequired();
            return defaultResponse;
        }
        int maxcount = post == null ? 10 : post.getInt("maxcount", 10);
        int depthx = post == null ? -1 : post.getInt("depth", -1);
        Integer depth = depthx == -1 ? null : depthx;
        String orderx = post == null ? "ANY" : post.get("order", "ANY");
        Snapshots.Order order = Snapshots.Order.valueOf(orderx);
        String statex = post == null ? Transactions.State.INVENTORY.name()
                : post.get("state", Transactions.State.INVENTORY.name());
        Transactions.State state = Transactions.State.valueOf(statex);
        String host = post == null ? null : post.get("host");
        Map<String, Revisions> iddate = Transactions.select(host, depth, order, maxcount, state);
        // now select the URL from the index for these ids in iddate and make an RSS feed
        RSSFeed rssfeed = new RSSFeed(Integer.MAX_VALUE);
        rssfeed.setChannel(new RSSMessage("Snapshot list for host = " + host + ", depth = " + depth
                + ", order = " + order + ", maxcount = " + maxcount, "", ""));
        for (Map.Entry<String, Revisions> e : iddate.entrySet()) {
            try {
                DigestURL u = e.getValue().url == null ? sb.index.fulltext().getURL(e.getKey())
                        : new DigestURL(e.getValue().url);
                if (u == null)
                    continue;
                RSSMessage message = new RSSMessage(u.toNormalform(true), "", u, e.getKey());
                message.setPubDate(e.getValue().dates[0]);
                rssfeed.addMessage(message);
            } catch (IOException ee) {
                ConcurrentLog.logException(ee);
            }
        }
        byte[] rssBinary = UTF8.getBytes(rssfeed.toString());
        return new ByteArrayInputStream(rssBinary);
    }

    // for the following methods we (mostly) need an url or a url hash
    if (post == null)
        post = new serverObjects();
    final boolean xml = ext.equals("xml");
    final boolean pdf = ext.equals("pdf");
    if (pdf && !authenticated) {
        defaultResponse.authenticationRequired();
        return defaultResponse;
    }
    final boolean pngjpg = ext.equals("png") || ext.equals(DEFAULT_EXT);
    String urlhash = post.get("urlhash", "");
    String url = post.get("url", "");
    DigestURL durl = null;
    if (urlhash.length() == 0 && url.length() > 0) {
        try {
            durl = new DigestURL(url);
            urlhash = ASCII.String(durl.hash());
        } catch (MalformedURLException e) {
        }
    }
    if (durl == null && urlhash.length() > 0) {
        try {
            durl = sb.index.fulltext().getURL(urlhash);
        } catch (IOException e) {
            ConcurrentLog.logException(e);
        }
    }

    if (ext.equals("json")) {
        // command interface: view and change a transaction state, get metadata about transactions in the past
        String command = post.get("command", "metadata");
        String statename = post.get("state");
        JSONObject result = new JSONObject();
        try {
            if (command.equals("status")) {
                // return a status of the transaction archive
                JSONObject sizes = new JSONObject();
                for (Map.Entry<String, Integer> state : Transactions.sizes().entrySet())
                    sizes.put(state.getKey(), state.getValue());
                result.put("size", sizes);
            } else if (command.equals("list")) {
                if (!authenticated) {
                    defaultResponse.authenticationRequired();
                    return defaultResponse;
                }
                // return a status of the transaction archive
                String host = post.get("host");
                String depth = post.get("depth");
                int depthi = depth == null ? -1 : Integer.parseInt(depth);
                for (Transactions.State state : statename == null
                        ? new Transactions.State[] { Transactions.State.INVENTORY, Transactions.State.ARCHIVE }
                        : new Transactions.State[] { Transactions.State.valueOf(statename) }) {
                    if (host == null) {
                        JSONObject hostCountInventory = new JSONObject();
                        for (String h : Transactions.listHosts(state)) {
                            int size = Transactions.listIDsSize(h, depthi, state);
                            if (size > 0)
                                hostCountInventory.put(h, size);
                        }
                        result.put("count." + state.name(), hostCountInventory);
                    } else {
                        TreeMap<Integer, Collection<Revisions>> ids = Transactions.listIDs(host, depthi, state);
                        if (ids == null) {
                            result.put("result", "fail");
                            result.put("comment", "no entries for host " + host + " found");
                        } else {
                            for (Map.Entry<Integer, Collection<Revisions>> entry : ids.entrySet()) {
                                for (Revisions r : entry.getValue()) {
                                    try {
                                        JSONObject metadata = new JSONObject();
                                        DigestURL u = r.url != null ? new DigestURL(r.url)
                                                : sb.index.fulltext().getURL(r.urlhash);
                                        metadata.put("url", u == null ? "unknown" : u.toNormalform(true));
                                        metadata.put("dates", r.dates);
                                        assert r.depth == entry.getKey().intValue();
                                        metadata.put("depth", entry.getKey().intValue());
                                        result.put(r.urlhash, metadata);
                                    } catch (IOException e) {
                                    }
                                }
                            }
                        }
                    }
                }
            } else if (command.equals("commit")) {
                if (!authenticated) {
                    defaultResponse.authenticationRequired();
                    return defaultResponse;
                }
                Revisions r = Transactions.commit(urlhash);
                if (r != null) {
                    result.put("result", "success");
                    result.put("depth", r.depth);
                    result.put("url", r.url);
                    result.put("dates", r.dates);
                } else {
                    result.put("result", "fail");
                }
                result.put("urlhash", urlhash);
            } else if (command.equals("rollback")) {
                if (!authenticated) {
                    defaultResponse.authenticationRequired();
                    return defaultResponse;
                }
                Revisions r = Transactions.rollback(urlhash);
                if (r != null) {
                    result.put("result", "success");
                    result.put("depth", r.depth);
                    result.put("url", r.url);
                    result.put("dates", r.dates);
                } else {
                    result.put("result", "fail");
                }
                result.put("urlhash", urlhash);
            } else if (command.equals("metadata")) {
                try {
                    Revisions r;
                    Transactions.State state = statename == null || statename.length() == 0 ? null
                            : Transactions.State.valueOf(statename);
                    if (state == null) {
                        r = Transactions.getRevisions(Transactions.State.INVENTORY, urlhash);
                        if (r != null)
                            state = Transactions.State.INVENTORY;
                        r = Transactions.getRevisions(Transactions.State.ARCHIVE, urlhash);
                        if (r != null)
                            state = Transactions.State.ARCHIVE;
                    } else {
                        r = Transactions.getRevisions(state, urlhash);
                    }
                    if (r != null) {
                        JSONObject metadata = new JSONObject();
                        DigestURL u;
                        u = r.url != null ? new DigestURL(r.url) : sb.index.fulltext().getURL(r.urlhash);
                        metadata.put("url", u == null ? "unknown" : u.toNormalform(true));
                        metadata.put("dates", r.dates);
                        metadata.put("depth", r.depth);
                        metadata.put("state", state.name());
                        result.put(r.urlhash, metadata);
                    }
                } catch (IOException | IllegalArgumentException e) {
                }
            }
        } catch (JSONException e) {
            ConcurrentLog.logException(e);
        }
        String json = result.toString();
        if (post.containsKey("callback"))
            json = post.get("callback") + "([" + json + "]);";
        return new ByteArrayInputStream(UTF8.getBytes(json));
    }

    // for the following methods we always need the durl to fetch data
    if (durl == null) {
        throw new TemplateMissingParameterException("Missing valid url or urlhash parameter");
    }

    if (xml) {
        Collection<File> xmlSnapshots = Transactions.findPaths(durl, "xml", Transactions.State.ANY);
        File xmlFile = null;
        if (xmlSnapshots.isEmpty()) {
            throw new TemplateProcessingException("Could not find the xml snapshot file.",
                    HttpStatus.SC_NOT_FOUND);
        }
        xmlFile = xmlSnapshots.iterator().next();
        try {
            byte[] xmlBinary = FileUtils.read(xmlFile);
            return new ByteArrayInputStream(xmlBinary);
        } catch (final IOException e) {
            ConcurrentLog.logException(e);
            throw new TemplateProcessingException("Could not read the xml snapshot file.");
        }
    }

    if (pdf || pngjpg) {
        Collection<File> pdfSnapshots = Transactions.findPaths(durl, "pdf", Transactions.State.INVENTORY);
        File pdfFile = null;
        if (pdfSnapshots.isEmpty()) {
            // if the client is authenticated, we create the pdf on the fly!
            if (!authenticated) {
                throw new TemplateProcessingException(
                        "Could not find the pdf snapshot file. You must be authenticated to generate one on the fly.",
                        HttpStatus.SC_NOT_FOUND);
            }
            SolrDocument sd = sb.index.fulltext().getMetadata(durl.hash());
            boolean success = false;
            if (sd == null) {
                success = Transactions.store(durl, new Date(), 99, false, true,
                        sb.getConfigBool(SwitchboardConstants.PROXY_TRANSPARENT_PROXY, false)
                                ? "http://127.0.0.1:" + sb.getConfigInt(SwitchboardConstants.SERVER_PORT, 8090)
                                : null,
                        sb.getConfig("crawler.http.acceptLanguage", null));
            } else {
                SolrInputDocument sid = sb.index.fulltext().getDefaultConfiguration().toSolrInputDocument(sd);
                success = Transactions.store(sid, false, true, true,
                        sb.getConfigBool(SwitchboardConstants.PROXY_TRANSPARENT_PROXY, false)
                                ? "http://127.0.0.1:" + sb.getConfigInt(SwitchboardConstants.SERVER_PORT, 8090)
                                : null,
                        sb.getConfig("crawler.http.acceptLanguage", null));
            }
            if (success) {
                pdfSnapshots = Transactions.findPaths(durl, "pdf", Transactions.State.ANY);
                if (!pdfSnapshots.isEmpty()) {
                    pdfFile = pdfSnapshots.iterator().next();
                }
            }
        } else {
            pdfFile = pdfSnapshots.iterator().next();
        }
        if (pdfFile == null) {
            throw new TemplateProcessingException(
                    "Could not find the pdf snapshot file and could not generate one on the fly.",
                    HttpStatus.SC_NOT_FOUND);
        }
        if (pdf) {
            try {
                byte[] pdfBinary = FileUtils.read(pdfFile);
                return new ByteArrayInputStream(pdfBinary);
            } catch (final IOException e) {
                ConcurrentLog.logException(e);
                throw new TemplateProcessingException("Could not read the pdf snapshot file.");
            }
        }

        if (pngjpg) {
            int width = Math.min(post.getInt("width", DEFAULT_WIDTH), DEFAULT_WIDTH);
            int height = Math.min(post.getInt("height", DEFAULT_HEIGHT), DEFAULT_HEIGHT);
            String imageFileStub = pdfFile.getAbsolutePath();
            imageFileStub = imageFileStub.substring(0, imageFileStub.length() - 3); // cut off extension
            File imageFile = new File(imageFileStub + DEFAULT_WIDTH + "." + DEFAULT_HEIGHT + "." + ext);
            if (!imageFile.exists() && authenticated) {
                if (!Html2Image.pdf2image(pdfFile, imageFile, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_DENSITY,
                        DEFAULT_QUALITY)) {
                    throw new TemplateProcessingException(
                            "Could not generate the " + ext + " image snapshot file.");
                }
            }
            if (!imageFile.exists()) {
                throw new TemplateProcessingException(
                        "Could not find the " + ext
                                + " image snapshot file. You must be authenticated to generate one on the fly.",
                        HttpStatus.SC_NOT_FOUND);
            }
            if (width == DEFAULT_WIDTH && height == DEFAULT_HEIGHT) {
                try {
                    byte[] imageBinary = FileUtils.read(imageFile);
                    return new ByteArrayInputStream(imageBinary);
                } catch (final IOException e) {
                    ConcurrentLog.logException(e);
                    throw new TemplateProcessingException(
                            "Could not read the " + ext + " image snapshot file.");
                }
            }
            // lets read the file and scale
            Image image;
            try {
                image = ImageParser.parse(imageFile.getAbsolutePath(), FileUtils.read(imageFile));
                if (image == null) {
                    throw new TemplateProcessingException(
                            "Could not parse the " + ext + " image snapshot file.");
                }
                final Image scaled = image.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) {
                }

                /*
                 * Ensure there is no alpha component on the ouput image, as it is pointless
                 * here and it is not well supported by the JPEGImageWriter from OpenJDK
                 */
                BufferedImage scaledBufferedImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                scaledBufferedImg.createGraphics().drawImage(scaled, 0, 0, width, height, null);
                return new EncodedImage(scaledBufferedImg, ext, true);
            } catch (final IOException e) {
                ConcurrentLog.logException(e);
                throw new TemplateProcessingException("Could not scale the " + ext + " image snapshot file.");
            }

        }
    }

    throw new TemplateProcessingException(
            "Unsupported extension : " + ext + ". Try with rss, xml, json, pdf, png or jpg.",
            HttpStatus.SC_BAD_REQUEST);
}

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  w  w w. j av a 2 s. 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:net.sf.firemox.tools.MToolKit.java

/**
 * Return the loaded picture from a local place.
 * /*from ww w  .  j  av  a  2 s  .  c  o  m*/
 * @param localFile
 *          the local file name.
 * @return the local picture.
 * @throws InterruptedException
 */
public static Image getLocalPicture(String localFile) throws InterruptedException {
    final Image result = Toolkit.getDefaultToolkit().getImage(getFile(localFile, true).getAbsolutePath());
    if (result == null) {
        throw new InterruptedException("Picture " + localFile + " has not been found");
    }
    final MediaTracker tracker = new MediaTracker(MagicUIComponents.magicForm);
    tracker.addImage(result, 0);
    tracker.waitForAll();
    if (tracker.isErrorAny()) {
        tracker.removeImage(result, 0);
        tracker.waitForAll();
        result.flush();
        throw new InterruptedException("Malformed picture " + localFile);
    }
    return result;
}

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

/**
 * Creates a new splash screen.//from w  w  w .  j ava 2s.com
 * 
 * @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 a  v  a  2  s .com*/
 * @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  w  w. j a va2s  . co  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);
}