Creating ImageIcon from Image is very slow

Hi I have a program which reads a number of files which may contain (amongst other things) image data in various formats such as JPG.I read scale this down into an image object fine, and then I want to display a small version of it on screen so I put the scale dimage into an ImageIcon which i display later using a JLabel.
Anyway it runs very slow , the funny thing is using JProbe Ive tracked the problem down to creation of the ImageIcon constructor, the actual thumbnail image creation is very quick.
Why does ImageIcon take so long or is there a simple way of displaying the image in a Swing Application
without using JLabel.
BufferedImage bi = ImageIO.read(new DataInputStream(new ByteArrayInputStream(imageData)));
Image thumbnaiImage = image.getScaledInstance(20,20Image.SCALE_FAST);
ImageIcon thumbnail     = new ImageIcon(thumbnailImage);

If you're not too picky about the image quality (and I see you're using SCALE_FAST), you can set the
source subsampling on your ImageReadParam so that you never construct the large image: you start
with the thumbnail.
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.*;
import javax.swing.*;
public class AllThumbs {
    public static void main(String[] args) throws MalformedURLException {
        String prefix = "http://www3.us.porsche.com/english/usa/carreragt/modelinformation/experience/desktop/bilder/icon";
        String suffix = "_800x600.jpg";
        JPanel p = new JPanel(new GridLayout(0,3));
        for(int i=1; i<9; ++i) {
            try {
                p.add(getThumb(new URL(prefix + i + suffix), 200, 150));
            } catch (IOException e) {
                System.out.println(e.getMessage());
        JFrame f = new JFrame("AllThumbs");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(p);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    public static JLabel getThumb(URL url, int maxWidth, int maxHeight) throws IOException {
        String suffix = getSuffix(url);
        Iterator readers = ImageIO.getImageReadersBySuffix(suffix);
        if (!readers.hasNext())
            throw new IOException("No reader for suffix " + suffix);
        ImageReader reader = (ImageReader) readers.next();
        reader.setInput(ImageIO.createImageInputStream(url.openStream()), true, true);
        int w = reader.getWidth(0), h = reader.getHeight(0);
        int subsampling = Math.max(1, Math.max(w/maxWidth, h/maxHeight));
        ImageReadParam param = reader.getDefaultReadParam();
        param.setSourceSubsampling(subsampling, subsampling, 0, 0);
        BufferedImage image = reader.read(0, param);
        String path = url.getPath();
        String text = path.substring(1+path.lastIndexOf('/'));
        JLabel label = new JLabel(text, new ImageIcon(image), SwingConstants.CENTER);
        label.setHorizontalTextPosition(SwingConstants.CENTER);
        label.setVerticalTextPosition(SwingConstants.BOTTOM);
        label.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
        return label;
    public static String getSuffix(URL url) throws IOException {
        String path = url.getPath();
        int dot = path.lastIndexOf('.');
        if (dot == -1)
            throw new IOException("No . in " + path);
        return path.substring(1+dot);
}It is also possible for there to be thumbnail images stored in an image file. (These thumbnails
don't even have to be related to the main image.) ImageIO has methods to read these directly,
so if you have control over your image files you can create them with thumbnails in place.

Similar Messages

  • Illustrator script to create symbols from images in folder

    Time to give back to the community...
    Here is a script I recently devised to bulk create symbols from images in a folder. Tested with Illustrator CC 2014.
    // Import Folder's Files as Symbols - Illustrator CC script
    // Description: Creates symbols from images in the designated folder into current document
    // Author     : Oscar Rines (oscarrines (at) gmail.com)
    // Version    : 1.0.0 on 2014-09-21
    // Reused code from "Import Folder's Files as Layers - Illustrator CS3 script"
    // by Nathaniel V. KELSO ([email protected])
    #target illustrator
    function getFolder() {
      return Folder.selectDialog('Please select the folder to be imported:', Folder('~'));
    function symbolExists(seekInDoc, seekSymbol) {
        for (var j=0; j < seekInDoc.symbols.length; j++) {
            if (seekInDoc.symbols[j].name == seekSymbol) {
                return true;
        return false;
    function importFolderContents(selectedFolder) {
        var activeDoc = app.activeDocument;     //Active object reference
      // if a folder was selected continue with action, otherwise quit
      if (selectedFolder) {
            var newsymbol;              //Symbol object reference
            var placedart;              //PlacedItem object reference
            var fname;                  //File name
            var sname;                  //Symbol name
            var symbolcount = 0;        //Number of symbols added
            var templayer = activeDoc.layers.add(); //Create a new temporary layer
            templayer.name = "Temporary layer"
            var imageList = selectedFolder.getFiles(); //retrieve files in the folder
            // Create a palette-type window (a modeless or floating dialog),
            var win = new Window("palette", "SnpCreateProgressBar", {x:100, y:100, width:750, height:310});
            win.pnl = win.add("panel", [10, 10, 740, 255], "Progress"); //add a panel to contain the components
            win.pnl.currentTaskLabel = win.pnl.add("statictext", [10, 18, 620, 33], "Examining: -"); //label indicating current file being examined
            win.pnl.progBarLabel = win.pnl.add("statictext", [620, 18, 720, 33], "0/0"); //progress bar label
            win.pnl.progBarLabel.justify = 'right';
            win.pnl.progBar = win.pnl.add("progressbar", [10, 35, 720, 60], 0, imageList.length-1); //progress bar
            win.pnl.symbolCount = win.pnl.add("statictext", [10, 70, 710, 85], "Symbols added: 0"); //label indicating number of symbols created
            win.pnl.symbolLabel = win.pnl.add("statictext", [10, 85, 710, 100], "Last added symbol: -"); //label indicating name of the symbol created
            win.pnl.errorListLabel = win.pnl.add("statictext", [10, 110, 720, 125], "Error log:"); //progress bar label
            win.pnl.errorList = win.pnl.add ("edittext", [10, 125, 720, 225], "", {multiline: true, scrolling: true}); //errorlist
            //win.pnl.errorList.graphics.font = ScriptUI.newFont ("Arial", "REGULAR", 7);
            //win.pnl.errorList.graphics.foregroundColor = win.pnl.errorList.graphics.newPen(ScriptUIGraphics.PenType.SOLID_COLOR, [1, 0, 0, 1], 1);
            win.doneButton = win.add("button", [640, 265, 740, 295], "OK"); //button to dispose the panel
            win.doneButton.onClick = function () //define behavior for the "Done" button
                win.close();
            win.center();
            win.show();
            //Iterate images
            for (var i = 0; i < imageList.length; i++) {
                win.pnl.currentTaskLabel.text = 'Examining: ' + imageList[i].name; //update current file indicator
                win.pnl.progBarLabel.text = i+1 + '/' + imageList.length; //update file count
                win.pnl.progBar.value = i+1; //update progress bar
                if (imageList[i] instanceof File) {         
                    fname = imageList[i].name.toLowerCase(); //convert file name to lowercase to check for supported formats
                    if( (fname.indexOf('.eps') == -1) &&
                        (fname.indexOf('.png') == -1)) {
                        win.pnl.errorList.text += 'Skipping ' + imageList[i].name + '. Not a supported type.\r'; //log error
                        continue; // skip unsupported formats
                    else {
                        sname = imageList[i].name.substring(0, imageList[i].name.lastIndexOf(".") ); //discard file extension
                        // Check for duplicate symbol name;
                        if (symbolExists(activeDoc, sname)) {
                            win.pnl.errorList.text += 'Skipping ' + imageList[i].name + '. Duplicate symbol for name: ' + sname + '\r'; //log error
                        else {
                            placedart = activeDoc.placedItems.add(); //get a reference to a new placedItem object
                            placedart.file = imageList[i]; //link the object to the image on disk
                            placedart.name =  sname; //give the placed item a name
                            placedart.embed();   //make this a RasterItem
                            placedart = activeDoc.rasterItems.getByName(sname); //get a reference to the newly created raster item
                            newsymbol = activeDoc.symbols.add(placedart); //add the raster item to the symbols                 
                            newsymbol.name = sname; //name the symbol
                            symbolcount++; //update the count of symbols created
                            placedart.remove(); //remove the raster item from the canvas
                            win.pnl.symbolCount.text = 'Symbols added: ' + symbolcount; //update created number of symbols indicator
                            win.pnl.symbolLabel.text = 'Last added symbol: ' + sname; //update created symbol indicator
                else {
                    win.pnl.errorList.text += 'Skipping ' + imageList[i].name + '. Not a regular file.\r'; //log error
                win.update(); //required so pop-up window content updates are shown
            win.pnl.currentTaskLabel.text = ''; //clear current file indicator
            // Final verdict
            if (symbolcount >0) {
                win.pnl.symbolLabel.text = 'Symbol library changed. Do not forget to save your work';
            else {
                win.pnl.symbolLabel.text = 'No new symbols added to the library';
            win.update(); //update window contents
            templayer.remove(); //remove the temporary layer
        else {
            alert("Action cancelled by user");
    if ( app.documents.length > 0 ) {
        importFolderContents( getFolder() );
    else{
        Window.alert("You must open at least one document.");

    Thank you, nice job & I am looking forward to trying it out!

  • Encrypted disk image creation very slow-

    I just got a new MBP with Leopard. I have created a number of encrypted disk images in the past using Tiger and a MBP and have not had any trouble. This weekend I tried a few times to create a 50 gig encrypted disk image (128 AES) on an external drive and after going through the process of setting it up and waiting for it to be created, (and watching the progress bar as it was being created), after about 45 minutes NO progress was showing on the progress bar. I ended up having to cancel the creation a few times because I thought something was going wrong. I’m not sure if there is a problem creating the disk image, or leopard is slow, or what.
    Does anyone know how long, on average, it would take to create an encrypted disk image of this size using leopard? I just want to know if there is a problem doing this on my MBP. Thanks for the help.

    A regular 50 GB disk image takes 50GB of space, no matter if it is full of files or empty.
    A 50 GB sparse disk image only takes up the amount of space equivalent to that of its enclosed files. So if the 50GB sparse image only has 1 GB of files inside, the image won't be much bigger than 1GB.
    A sparse bundle is similar to a sparse image, but instead of a single file it is a folder package with many, many enclosed files called bands. A new file added to the sparse bundle will tend to modify only a few bands. This makes incremental backups of a sparse bundle more efficient because only the changed bands need to be backed up again. Any change to a sparse or regular disk image will mean that the entire image will need to be backed up again.
    If you regularly add/remove files to a disk image, and you intend to back up that disk image with Time Machine, a sparse bundle is definitely the way to go. The other types will fill up your TM volume very quickly.

  • E book bought from Waterstones is very slow in use can you, help?

    E book bought from Waterstones is unreasonably slow in use can you help, please?
    I purchased a copy of “The Complete English Poems” by John Donne as an e-book, I downloaded the e-book successfully, as well as the new Digital Editions software and transferred the e-book to my Sony Reader. However when I try to use the book it is slow opening up and very slow moving between sections, or navigating between the poem and the notes on the poems, typically between three and five minutes. In practice this means that if I wish to consult a note on a poem it can take five minutes to move from the poem to the note then another five minutes to navigate back, giving a time of ten minutes to consult a note. This is not really feasible.
    I have had no problem downloading and reading other books, from Waterstones bought after the John Donne.
    I have tried deleting and re-loading the John Donne, as well as resetting the reader to no avail.
    I contacted Sony support who says that as my other e-books from Waterstones and other sources work perfectly, then the fault lies with “The Complete English Poems” and not the Sony reader.
    Please note that I had a similar problem with a Waterstones edition of “the King James Version of The Holy Bible. “ This problem was never resolved.

    You need to install more RAM.
    Your year and model IMac can take a total of 6 GBs of RAM.
    Correct, compatible and reliable Mac RAM can ONLY be purchased from online RAM sources Crucial memory or OWC (macsales.com).
    The 6 GB RAM kit can be found here.
    http://eshop.macsales.com/shop/memory/iMac/Intel_Core_2_Duo_PC2-6400
    If you haven't use this application often, completely uninstall CleanMyMac.
    Total, useless "junkware"/"Garbageware"/malware.
    http://macpaw.com/support/cleanmymac-classic/knowledgebase/how-to-uninstall-clea nmymac-classic
    http://macpaw.com/support/cleanmymac/knowledgebase/how-to-uninstall-cleanmymac-2
    Ditch ALL Googlewares. They are ALL a serious resource hog on the OS X system.
    https://support.google.com/chrome/answer/95319?hl=en
    https://support.google.com/drive/answer/2375081?hl=en
    If you do not like Apple's Safari web browser, download, install and try Mozilla FireFox, instead.
    The current, up-to-date version of FireFox is fully compatible with OS X and is regularly updated by the great developers of the Mozilla group.
    I have, also, stopped using the Google search engine, regularly and use DuckDuckGo as my default search engine.
    You have too many and duplicate user login/startup items.
    Add or remove automatic items
    Choose Apple menu > System Preferences, then click Users & Groups.
    Select your user account, then click Login Items.
    Do one of the following:
    Click Add below the list on the right, select an app, document, folder, or disk, then click Add.
    If you don’t want an item’s windows to be visible after login, select Hide. (Hide does not apply to servers, which always appear in the Finder after login.)
    Select the name of the item you want to prevent from opening automatically, then click Delete below the list on the right.

  • Creating text boxes is causing VERY slow performance

    i've read the threads about how slow indesign cc has been from last year.  i would assume this issue had been fixed by now, so i just switched our
    whole company over from cs5 to cc.  we are a prinitng company that makes calendars with many text boxes, and indesign cc is about 1/2 as fast
    as cs5 was in creating these from scratch.  i've noticed the more text boxes, whether used or blank, causes it to slow even more.  i can't do anything
    without it lagging and pausing, which is not productive whatsoever.
    is there any fix at all to this or is this ever going to be fixed?  i have found no solution. 
    we have 32 gb ram and decently fast macs (not the newest but decent), but processing speed can't be the issue when it seems everyone is having these same problems.  (we do not have retina dislplays, just normal samsung monitors)
    we have tried saving new files out as the new cc version but that doesn't help.
    try it for yourself.  make an 8 1/2 X 11 document with 100 step and repeated text boxes.  even left blank, the whole programs slows down.
    i need help, or else i have no choice but to roll everyone back to cs5.

    You did receive the file.  You already replied to me about the issue.  See below.
    Since I have last spoken with you I did download os 10.7.5, and I will work with it today to see if it's any faster.  Unfortunately as I predicted it  "broke" 2 of our other powerpc applications that I absolutely have to have, so that's a whole other set of issues that this has caused me.
    I will let you know if I still have the same performance issues.  This is the last thing I can try because I cannot upgrade this mac to 10.8.  If the performance isn't better I guess I'll just be forced to go back to CS5.
    Chris Smith
    Drum-Line Graphics Dept. Manager
    800-284-2456 Ext. 133
    Hi Chris,
    We are officially NOT supporting 10.6.8. The official supported platforms of Mac are 10.7 onwards.
    I too would recommend that you upgrade as we haven't performed much testing on 10.6.8. It currently works but the outcome may not be nice as you are already facing.
    Maybe you can try upgrading to 10.7 or 10.8, your mac may support these platforms and so does InDesign.
    Thanks
    Javed

  • Retrieving record from oracle DB very slow..pls help

    Hi, i'm writing a VB code to retrieving records from Oracle DB Server version 8. I'm using VB Adodb to retrieve the records from various tables. Unfortunately one of the table are very slow to response, the table only contain around 204900 records. The SQL Statement to retrieve the records is a simple SQL Statement that contain WHERE clause only. Any issue that will make the retrieving time become slow? Is that a Indexing? Oracle Driver? Hardware Spec? Or any solution for me to improve the performance. Thanks!

    Well, there are a few things to consider...
    First, can you try executing your query via SQL*Plus? If there are database tuning problems, your query will be slow no matter where you run it.
    Second, are you retrieving significantly more rows in this query than in your other queries? It can take a significant amount of time to retrieve records to the client, even if it's quick to select them.
    Justin

  • Creating video from images

    I am trying to make video from images
    here is my program
    import java.awt.Dimension;
    import java.awt.Image;
    import javax.media.*;
    import javax.media.control.*;
    import javax.media.protocol.*;
    import javax.media.protocol.DataSource;
    import javax.media.datasink.*;
    import javax.media.format.VideoFormat;
    import javax.media.util.ImageToBuffer;
    import java.io.*;
    import java.util.*;
    *For AVI files, each frame must have a time stamp set. See the following message from the jmf-interest archives for details:
    http://archives.java.sun.com/cgi-bin/wa?A2=ind0107&L=jmf-interest&P=R34660
    public class AviCreator implements ControllerListener, DataSinkListener
    private boolean doIt(
    int width,
    int height,
    int frameRate,
    MediaLocator outML)
         File folder=new File("c:/images1");     
              File [] files=folder.listFiles();
    ImageDataSource ids = new ImageDataSource(width, height, frameRate,files);
    Processor p;
    try
    System.err.println(
    "- create processor for the image datasource ...");
    p = Manager.createProcessor(ids);
    catch (Exception e)
    System.err.println(
    "Yikes! Cannot create a processor from the data source.");
    return false;
    p.addControllerListener(this);
    // Put the Processor into configured state so we can set
    // some processing options on the processor.
    p.configure();
    if (!waitForState(p, Processor.Configured))
    System.err.println("Failed to configure the processor.");
    return false;
    // Set the output content descriptor to QuickTime.
    p.setContentDescriptor(
    new ContentDescriptor(FileTypeDescriptor.MSVIDEO));
    // Query for the processor for supported formats.
    // Then set it on the processor.
    TrackControl tcs[] = p.getTrackControls();
    Format f[] = tcs[0].getSupportedFormats();
    if (f == null || f.length <= 0)
    System.err.println(
    "The mux does not support the input format: "
    + tcs[0].getFormat());
    return false;
    tcs[0].setFormat(f[0]);
    System.err.println("Setting the track format to: " + f[0]);
    // We are done with programming the processor. Let's just
    // realize it.
    p.realize();
    if (!waitForState(p, Processor.Realized))
    System.err.println("Failed to realize the processor.");
    return false;
    // Now, we'll need to create a DataSink.
    DataSink dsink;
    if ((dsink = createDataSink(p, outML)) == null)
    System.err.println(
    "Failed to create a DataSink for the given output MediaLocator: "
    + outML);
    return false;
    dsink.addDataSinkListener(this);
    fileDone = false;
    System.err.println("start processing...");
    // OK, we can now start the actual transcoding.
    try
    p.start();
    dsink.start();
    catch (IOException e)
    System.err.println("IO error during processing");
    return false;
    // Wait for EndOfStream event.
    waitForFileDone();
    // Cleanup.
    try
    dsink.close();
    catch (Exception e)
    p.removeControllerListener(this);
    System.err.println("...done processing.");
    return true;
    * Create the DataSink.
    private DataSink createDataSink(Processor p, MediaLocator outML)
    DataSource ds;
    if ((ds = p.getDataOutput()) == null)
    System.err.println(
    "Something is really wrong: the processor does not have an output DataSource");
    return null;
    DataSink dsink;
    try
    System.err.println("- create DataSink for: " + outML);
    dsink = Manager.createDataSink(ds, outML);
    dsink.open();
    catch (Exception e)
    System.err.println("Cannot create the DataSink: " + e);
    return null;
    return dsink;
    private Object waitSync = new Object();
    private boolean stateTransitionOK = true;
    * Block until the processor has transitioned to the given state.
    * Return false if the transition failed.
    private boolean waitForState(Processor p, int state)
    synchronized (waitSync)
    try
    while (p.getState() < state && stateTransitionOK)
    waitSync.wait();
    catch (Exception e)
    return stateTransitionOK;
    * Controller Listener.
    public void controllerUpdate(ControllerEvent evt)
    if (evt instanceof ConfigureCompleteEvent
    || evt instanceof RealizeCompleteEvent
    || evt instanceof PrefetchCompleteEvent)
    synchronized (waitSync)
    stateTransitionOK = true;
    waitSync.notifyAll();
    else if (evt instanceof ResourceUnavailableEvent)
    synchronized (waitSync)
    stateTransitionOK = false;
    waitSync.notifyAll();
    else if (evt instanceof EndOfMediaEvent)
    evt.getSourceController().stop();
    evt.getSourceController().close();
    private Object waitFileSync = new Object();
    private boolean fileDone = false;
    private boolean fileSuccess = true;
    * Block until file writing is done.
    private boolean waitForFileDone()
    synchronized (waitFileSync)
    try
    while (!fileDone)
    waitFileSync.wait();
    catch (Exception e)
    return fileSuccess;
    * Event handler for the file writer.
    public void dataSinkUpdate(DataSinkEvent evt)
    if (evt instanceof EndOfStreamEvent)
    synchronized (waitFileSync)
    fileDone = true;
    waitFileSync.notifyAll();
    else if (evt instanceof DataSinkErrorEvent)
    synchronized (waitFileSync)
    fileDone = true;
    fileSuccess = false;
    waitFileSync.notifyAll();
    public static String[] createParam()
         File folder=new File("c:/images1");     
         String [] files=folder.list();
         String param[]=new String[files.length+8];          
    param[0]="-w";
    param[1]="400";
    param[2]="-h";
    param[3]="300";
    param[4]="-f";
    param[5]="1";
    param[6]="-o";
    param[7]="file:/c:/images/abc.avi";          
         for(int i=8;i<files.length+8;i++)     
              param="file:/c:/images1/"+files[i-8];
    return param;     
    public static void main(String args1[]) throws Exception
    //jpegCreator.main(null);
    //if (args.length == 0)
    // prUsage();
              //String [] args ={"-w","320" ,"-h","240", "-f","1", "-o", "file:/c:/images/abc.mov","file:/c:/images/surya_jo1.jpg", "file:/c:/temp/flower1_jpg.jpg" };
              String [] args=createParam();
    // Parse the arguments.
    int i = 0;
    int width = -1, height = -1, frameRate = 1;
    Vector inputFiles = new Vector();
    inputFiles.add("file:/c:/images/surya_jo1.jpg");
    inputFiles.add("file:/c:/images/flower1_jpg.jpg");
    String outputURL = null;
    width = 128;
    height = 128;
    outputURL = "file:/c:/images/abc.avi";
    // Generate the output media locators.
    MediaLocator oml;
    if ((oml = createMediaLocator(outputURL)) == null)
    System.err.println("Cannot build media locator from: " + outputURL);
    System.exit(0);
    AviCreator imageToMovie = new AviCreator();
    imageToMovie.doIt(width, height, frameRate, oml);
    System.exit(0);
    static void prUsage()
    System.err.println(
    "Usage: java JpegImagesToMovie -w <width> -h <height> -f <frame rate> -o <output URL> <input JPEG file 1> <input JPEG file 2> ...");
    System.exit(-1);
    * Create a media locator from the given string.
    private static MediaLocator createMediaLocator(String url)
    MediaLocator ml;
    if (url.indexOf(":") > 0 && (ml = new MediaLocator(url)) != null)
    return ml;
    if (url.startsWith(File.separator))
    if ((ml = new MediaLocator("file:" + url)) != null)
    return ml;
    else
    String file =
    "file:" + System.getProperty("user.dir") + File.separator + url;
    if ((ml = new MediaLocator(file)) != null)
    return ml;
    return null;
    // Inner classes.
    * A DataSource to read from a list of JPEG image files and
    * turn that into a stream of JMF buffers.
    * The DataSource is not seekable or positionable.
    /************************************************* private class ImageDataSource extends PullBufferDataSource
    private ImageSourceStream streams[];
    ImageDataSource(int width, int height, int frameRate)
    streams = new ImageSourceStream[1];
    streams[0] = new ImageSourceStream(width, height, frameRate);
    public void setLocator(MediaLocator source)
    public MediaLocator getLocator()
    return null;
    public String getContentType()
    return ContentDescriptor.RAW;
    public void connect()
    public void disconnect()
    public void start()
    public void stop()
    public PullBufferStream[] getStreams()
    return streams;
    public Time getDuration()
    System.out.println("dur is " + streams[0].nextImage);
    //return new Time(1000000000);
    return DURATION_UNKNOWN;
    public Object[] getControls()
    return new Object[0];
    public Object getControl(String type)
    return null;
    * A DataSource to read from a list of JPEG image files or
    * java.awt.Images, and
    * turn that into a stream of JMF buffers.
    * The DataSource is not seekable or positionable.
    private static class ImageDataSource extends PullBufferDataSource {
    private final Time durTime;
    private final PullBufferStream[] streams = new JpegSourceStream[1];
    * Constructor for creating movies out of jpegs
    ImageDataSource(int width, int height, int frameRate, File[] jpegFiles) {
    streams[0] = new JpegSourceStream(width, height, frameRate, jpegFiles);
    this.durTime = new Time(jpegFiles.length / frameRate);
    * Constructor for creating movies out of Images
    * NOTE - this is all done IN MEMORY, so you'd better have enough
    /*ImageDataSource(int width, int height, int frameRate, Image[] images) {
    streams[0] = new AWTImageSourceStream(width, height, frameRate, images);
    this.durTime = new Time(images.length / frameRate);
    public void setLocator(MediaLocator source) {
    public MediaLocator getLocator() {
    return null;
    * Content type is of RAW since we are sending buffers of video
    * frames without a container format.
    public String getContentType() {
    return ContentDescriptor.RAW;
    public void connect() {
    public void disconnect() {
    public void start() {
    public void stop() {
    * Return the ImageSourceStreams.
    public PullBufferStream[] getStreams() {
    return streams;
    public Time getDuration() {
    return durTime;
    public Object[] getControls() {
    return new Object[0];
    public Object getControl(String type) {
    return null;
    * The jpeg-based source stream to go along with ImageDataSource.
    private static class JpegSourceStream implements PullBufferStream {
    private final File[] jpegFiles;
    private final int width, height;
    private final VideoFormat videoFormat;
    private int nextImage = 0; // index of the next image to be read.
    private boolean ended = false;
    // Bug fix from Forums - next one line
    long seqNo = 0;
    public JpegSourceStream(int width, int height, int frameRate, File[] jpegFiles) {
    this.width = width;
    this.height = height;
    this.jpegFiles = jpegFiles;
    this.videoFormat = new VideoFormat(VideoFormat.JPEG,
    new Dimension(width, height),
    Format.NOT_SPECIFIED,
    Format.byteArray,
    (float)frameRate);
    * We should never need to block assuming data are read from files.
    public boolean willReadBlock() {
    return false;
    * This is called from the Processor to read a frame worth
    * of video data.
    public void read(final Buffer buf) {
    try {
    // Check if we've finished all the frames.
    if (nextImage >= jpegFiles.length) {
    // We are done. Set EndOfMedia.
    System.out.println("Done reading all images.");
    buf.setEOM(true);
    buf.setOffset(0);
    buf.setLength(0);
    ended = true;
    return;
    File imageFile = jpegFiles[nextImage];
    nextImage++;
    System.out.println(" - reading image file: " + imageFile);
    // Open a random access file for the next image.
    RandomAccessFile raFile = new RandomAccessFile(imageFile, "r");
    byte[] data = (byte[])buf.getData();
    // Check to see the given buffer is big enough for the frame.
    if (data == null || data.length < raFile.length()) {
    // allocate larger buffer
    data = new byte[(int)raFile.length()];
    buf.setData(data);
    // Read the entire JPEG image from the file.
    raFile.readFully(data, 0, (int)raFile.length());
    System.out.println(" read " + raFile.length() + " bytes.");
    // Bug fix for AVI files from Forums ( next 3 lines).
    long time = (long) (seqNo * (1000 / videoFormat.getFrameRate()) * 1000000);
    buf.setTimeStamp(time);
    buf.setSequenceNumber(seqNo++);
    buf.setOffset(0);
    buf.setLength((int)raFile.length());
    buf.setFormat(videoFormat);
    buf.setFlags(buf.getFlags() | buf.FLAG_KEY_FRAME);
    // Close the random access file.
    raFile.close();
    } catch (Exception e) {
    // it's important to print the stack trace here because the
    // sun class that calls this method silently ignores
    // any IOExceptions that get thrown
    e.printStackTrace();
    throw new RuntimeException(e);
    * Return the format of each video frame. That will be JPEG.
    public Format getFormat() {
    return videoFormat;
    public ContentDescriptor getContentDescriptor() {
    return new ContentDescriptor(ContentDescriptor.RAW);
    public long getContentLength() {
    return LENGTH_UNKNOWN;
    public boolean endOfStream() {
    return ended;
    public Object[] getControls() {
    return new Object[0];
    public Object getControl(String type) {
    return null;
    * The source stream to go along with ImageDataSource.
    /*************************************************************** class ImageSourceStream implements PullBufferStream
    final int width, height;
    final VideoFormat format;
    // Bug fix from Forums - next two lines
    float frameRate;
    long seqNo = 0;
    int nextImage = 0; // index of the next image to be read.
    boolean ended = false;
    public ImageSourceStream(int width, int height, int frameRate)
    this.width = width;
    this.height = height;
    // Bug fix from Forums (next line)
    this.frameRate = (float) frameRate;
    final int rMask = 0x00ff0000;
    final int gMask = 0x0000FF00;
    final int bMask = 0x000000ff;
    format =
    new javax.media.format.RGBFormat(
    new Dimension(width, height),
    Format.NOT_SPECIFIED,
    Format.intArray,
    frameRate,
    32,
    rMask,
    gMask,
    bMask);
    public boolean willReadBlock()
    return false;
    public void read(Buffer buf) throws IOException
    // Check if we've finished all the frames.
    if (nextImage >= 100)
    // We are done. Set EndOfMedia.
    System.err.println("Done reading all images.");
    buf.setEOM(true);
    buf.setOffset(0);
    buf.setLength(0);
    ended = true;
    return;
    nextImage++;
    int data[] = null;
    // Check the input buffer type & size.
    if (buf.getData() instanceof int[])
    data = (int[]) buf.getData();
    // Check to see the given buffer is big enough for the frame.
    if (data == null || data.length < width * height)
    data = new int[width * height];
    buf.setData(data);
    // Bug fix from Forums ( next 3 lines).
    long time = (long) (seqNo * (1000 / frameRate) * 1000000);
    buf.setTimeStamp(time);
    buf.setSequenceNumber(seqNo++);
    java.awt.Color clr = java.awt.Color.red;
    if (nextImage > 30)
    clr = java.awt.Color.GREEN;
    if (nextImage > 60)
    clr = java.awt.Color.BLUE;
    for (int i = 0; i < width * height; i++)
    // TODO - figure what the guy was trying to do here.
    data[i] = clr.getRGB();
    buf.setOffset(0);
    buf.setLength(width * height);
    buf.setFormat(format);
    buf.setFlags(buf.getFlags() | Buffer.FLAG_KEY_FRAME);
    public Format getFormat()
    return format;
    public ContentDescriptor getContentDescriptor()
    return new ContentDescriptor(ContentDescriptor.RAW);
    public long getContentLength()
    return 0;
    public boolean endOfStream()
    return ended;
    public Object[] getControls()
    return new Object[0];
    public Object getControl(String type)
    return null;
    * The java.awt.Image-based source stream to go along with ImageDataSource.
    * Not sure yet if this class works.
    private static class AWTImageSourceStream implements PullBufferStream {
    private final Image[] images;
    private final int width, height;
    private final VideoFormat videoFormat;
    private int nextImage = 0; // index of the next image to be read.
    private boolean ended = false;
    // Bug fix from Forums - next one line
    private long seqNo = 0;
    public AWTImageSourceStream(int width, int height, int frameRate, Image[] images) {
    this.width = width;
    this.height = height;
    this.images = images;
    // not sure if this is correct, especially the VideoFormat value
    this.videoFormat = new VideoFormat(VideoFormat.RGB,
    new Dimension(width, height),
    Format.NOT_SPECIFIED,
    Format.byteArray,
    (float)frameRate);
    * We should never need to block assuming data are read from files.
    public boolean willReadBlock() {
    return false;
    * This is called from the Processor to read a frame worth
    * of video data.
    public void read(final Buffer buf) throws IOException {
    try {
    // Check if we've finished all the frames.
    if (nextImage >= images.length) {
    // We are done. Set EndOfMedia.
    System.out.println("Done reading all images.");
    buf.setEOM(true);
    buf.setOffset(0);
    buf.setLength(0);
    ended = true;
    return;
    Image image = images[nextImage];
    nextImage++;
    // Open a random access file for the next image.
    //RandomAccessFile raFile = new RandomAccessFile(imageFile, "r");
    Buffer myBuffer = ImageToBuffer.createBuffer(image, videoFormat.getFrameRate());
    buf.copy(myBuffer);
    // Bug fix for AVI files from Forums ( next 3 lines).
    long time = (long) (seqNo * (1000 / videoFormat.getFrameRate()) * 1000000);
    buf.setTimeStamp(time);
    buf.setSequenceNumber(seqNo++);
    //buf.setOffset(0);
    //buf.setLength((int)raFile.length());
    //buf.setFormat(videoFormat);
    //buf.setFlags(buf.getFlags() | buf.FLAG_KEY_FRAME);
    } catch (Exception e) {
    // it's important to print the stack trace here because the
    // sun class that calls this method silently ignores
    // any Exceptions that get thrown
    e.printStackTrace();
    throw new RuntimeException(e);
    * Return the format of each video frame.
    public Format getFormat() {
    return videoFormat;
    public ContentDescriptor getContentDescriptor() {
    return new ContentDescriptor(ContentDescriptor.RAW);
    public long getContentLength() {
    return LENGTH_UNKNOWN;
    public boolean endOfStream() {
    return ended;
    public Object[] getControls() {
    return new Object[0];
    public Object getControl(String type) {
    return null;
    bit i am getting following exception at run time
    1
    2
    3
    4
    5
    6
    - create processor for the image datasource ...
    Setting the track format to: JPEG
    - create DataSink for: file:/c:/images/abc.mov
    start processing...
    - reading image file: file:/c:/images/surya_jo1.jpg
    - reading image file: file:/c:/images/flower1_jpg.jpg
    Done reading all images.
    Exception in thread "JMF thread: SendEventQueue: com.sun.media.processor.unknown.Handler" java.lang.NullPointerException
    at com.sun.media.multiplexer.video.QuicktimeMux.writeVideoSampleDescription(QuicktimeMux.java:936)
    at com.sun.media.multiplexer.video.QuicktimeMux.writeSTSD(QuicktimeMux.java:925)
    at com.sun.media.multiplexer.video.QuicktimeMux.writeSTBL(QuicktimeMux.java:905)
    at com.sun.media.multiplexer.video.QuicktimeMux.writeMINF(QuicktimeMux.java:806)
    at com.sun.media.multiplexer.video.QuicktimeMux.writeMDIA(QuicktimeMux.java:727)
    at com.sun.media.multiplexer.video.QuicktimeMux.writeTRAK(QuicktimeMux.java:644)
    at com.sun.media.multiplexer.video.QuicktimeMux.writeMOOV(QuicktimeMux.java:582)
    at com.sun.media.multiplexer.video.QuicktimeMux.writeFooter(QuicktimeMux.java:519)
    at com.sun.media.multiplexer.BasicMux.close(BasicMux.java:142)
    at com.sun.media.BasicMuxModule.doClose(BasicMuxModule.java:172)
    at com.sun.media.PlaybackEngine.doClose(PlaybackEngine.java:872)
    at com.sun.media.BasicController.close(BasicController.java:261)
    at com.sun.media.BasicPlayer.doClose(BasicPlayer.java:229)
    at com.sun.media.BasicController.close(BasicController.java:261)
    at JpegImagesToMovie.controllerUpdate(JpegImagesToMovie.java:196)
    at com.sun.media.BasicController.dispatchEvent(BasicController.java:1254)
    at com.sun.media.SendEventQueue.processEvent(BasicController.java:1286)
    at com.sun.media.util.ThreadedEventQueue.dispatchEvents(ThreadedEventQueue.java:65)
    at com.sun.media.util.ThreadedEventQueue.run(ThreadedEventQueue.java:92)
    plz help me
    thanks in advance

    Step 1) Copy that code into a .java file
    Step 2) Compile it
    Step 3) Run it
    Step 4) Look at the output
    Step 5 (optional)) If it didn't work, post a specific question about the code, and use [co[b]de] tags.

  • Create thumnail from image

    Can we create thumbnail from a image in Oracle 11g database?

    The image is stored as blob secure file in oracle 11g database.
    What is the difference between blob and ORDImage?
    Can I create thumbnail from a image and store it in the database?

  • Creating links to other topics very slow

    Hi, I have RH 7 and when creating links from one topic to
    another it takes a long time for the dialog boxes to appear. I have
    about 10 links per topic and at three minutes per link, that's a
    lot of time. Thanks, Becky

    I'm having the same, or a similar, problem. I'm trying to
    insert lots (more than a thousand) of help jumps into a Word 2007
    document and it's taking a minute or so per topic. I'm running on a
    laptop with an electronic disk. I don't see any CPD files to
    delete. I tried dragging a help topic from my project window to the
    Word document, but that didn't seem to do anything. Something I
    thought would work, but whch didn't, was to create the links as
    Word 2007 links (which is fast), then do a conversion and convert
    links to help jumps. I still haven't figured out why that didn't
    work. If there are any other suggestions, that would be
    appreciated.
    William

  • Downloading from iTunes Store very slow

    I am using iTunes 11.1.3 and download to my external hard drive on my MacBook Pro version OS X 10.9. I haven't had a problem with download speeds until now. Downloading a 22.5mb TV show is taking up to 3hrs. My internet (wireless) is running fine elsewhere in my home. I can watch apple tv via itunes store purchases just fine streaming as well as Netfix. Suggestions?

    Hey there Kimber.c,
    It sounds like your Wi-Fi connection is very slow on this computer. I would try the steps in this section of the article named:
    Wi-Fi: How to troubleshoot Wi-Fi connectivity
    http://support.apple.com/kb/HT4628?viewlocale=en_US
    Symptom: The Wi-Fi network seems slow
    Streaming movies may skip or pause.
    iTunes or other downloads may take an unusually long time to complete.
    Webpages may not load quickly.
    Thank you for using Apple Support Communities.
    All the very best,
    Sterling

  • Javascript to create vector from image and save as eps

    Hi,
    I started writing a script which open all images in a folder and i need to turn those into vectors.
    How do i write the following in JavaScript:
    Open the JPG file
    Select the image layer/object
    Create a vector from the image using the Image Trace for high fidelity 
    Reduce the new vector objec size by %50.
    save as eps
    any help with any of the stages would be very helpful.
    thank you

    PERFECT!!!!!!
    This is exactly what I was going to build.  No need to create when it is already done.
    Thank you very much.
    -Mike

  • Unusual Bug when creating pdf from image files

    Hi I have a very mindboggling problem which I cant seem to get my head around.
    basically I am trying to create a pdf using a large amount of image files, these images are scans of pages of a book. so I have been trying to create a pdf file from these images, and everytime i try, it all looks ok except for one page which comes up smaller in size than the rest which is a big problem and very unusual. If I change the view of acrobat so that it shows two pages at a time then this is clearly visable where one page is normal and the page next to it is like a third of the size. Ive checked the image file properties for that page and they are more or less the same as the rest, the dimensions of the image file too, but when I add it into a PDF it seems to shrink in size, any ideas as to why? any help would be much appreciated! (and I hope what I said made sense lol )
    Thanks
    Nav

    Hi Davew000
    Can you please tell the steps you are doing to create the PDF ?
    Thanks,
    Tanvi

  • Creating BufferedImage from Image

    I've figured out one way to create a BufferedImage from an Image, but I'm sure it's not the best way.Image im = Toolkit.getDefaultToolkit().getImage(files.getAbsolutePath());
    JLabel jl = new JLabel(new ImageIcon(im));
    BufferedImage bim = new BufferedImage(im.getWidth(null), im.getHeight(null), BufferedImage.TYPE_BYTE_INDEXED);
    Graphics g = bim.getGraphics();
    jl.paint(bim.getGraphics());
    This works, but I'm sure there has to be a better/easier way. Any suggestions?
    Thanks,
    m

    close, the best way is this...
    public BufferedImage createBufferedImage(Image img)
    BufferedImage bimg = new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_INT_RGB);//or whatever type is appropriate
    bimg.getGraphics().drawImage(img,0,0,null);
    return bimg;
    }

  • Viewing full screen images gets very slow in PSE 5&6

    In full screen preview mode, when going from a horizontal image to a vertical image, it takes several seconds to go to the next image.Have tried turning off and on the resizing option and it had no effect. Viewing 2mb jpgs from a Nikon D200.Have Win XP 64, 8GB Ram, dual core processor and a middle of the road video card.
    Could this be a video card issue? Would going to PSE 8 help. does PSE 8 utilize 64 bit OS?

    Very interesting.  I'm guessing that the portrait photos were rotated by the camera by setting the Orientation field in the photos' metadata, and that for some reason, PSE on your system requires a lot of time to properly rotate them on the fly in Full Screen view.  When you edit the photo in the Editor, it rotates the actual image, rather than setting the Orientation field.
    For a couple of test photos, try following steps 1 - 3 of this FAQ:
    http://www.johnrellis.com/psedbtool/photoshop-elements-faq.htm#_Photos_not_properly
    This should have the same effect as editing them in the Editor.

  • Opening Aperture Library from my Drobo (Very Slow)

    I have a Firewire Drobo, which I love, and I use Aperture on my Mac. I currently have my primary Aperture Library (~125GB) on my Drobo. I have been experiencing an issue with slowness when opening my Aperture library from my Drobo. It takes several minutes (5-6) to open my library from the Drobo and am wondering if 1) others are experiencing excessive slowness when opening their Aperture Library from a Drobo and/or 2) if I would be better off just using a regular firewire drive for my Aperture library and using the Drobo just for my Aperture Vault and not my primary library?
    It seems that this issue has gradually gotten worse as my library has increased in size. When the library was 50GB it seemed to open pretty quickly, but the bigger it gets the longer it takes to open. Once it is open it is fairly snappy, although if I am reading and writing a lot of data to the Drobo simultaneously I will see some slowness sometimes. This machine is the current generation of 24" iMac with 4GB of RAM. My Drobo is filled with 3 - 1TB Western Digital Green drives and 1 500GB WD Green drive.
    Would love to hear if others are having a similar experience and any ideas for better performance.
    Thanks!
    Guy

    I don't think the FW is the problem, although it might be
    I was keeping my Aperture library on a Drobo and ALL of the images were referenced and not managed.
    And like you, it became progressively slower (5-10-15-20 minutes to open) and then became corrupted on more than one occasion. After the last episode and after substantial heroic efforts (48 hours of rebuilding), I was able to recover the library. Once recovered, I moved the library to my internal drive and left all of my images as referenced on the Drobo. The library since the move has been fine. I have occasional images which appear to become corrupted on the Drobo (not recognizable by Aperture or Photoshop or Preview), that fortunately, I simply replace the RAW file in the appropriate location from a back up copy of the RAW file and everything is fine.
    This has been discussed with Data Robotics and after several weeks I still don't have an answer from an email I sent providing all the requested information.
    Bottom Line. Place your referenced your images on Drobo, but make sure you have at least two other additional backup of your original datafiles. Move your library to some other drive immediately!!
    My suspicion is Aperture and Drobo RAID system do not work well together and Data Robotics has been disappointing in terms of technical response to inquiries.
    I have two Drobo boxes and they are used daily, but at this point I always, always always have at least two back ups on whatever is on the Drobo. My dream was it would be a highly or super reliable copy of my data, but at this point, I really do not consider them to be even a reliable copy, given the random corruption issues and Data Robotics poor support.
    I am investigating alternative large data systems and the most interesting thus far is the WD Share gigabit system. Data Robotics says that they only certify one other FW drive and it HAS to be a Data Robotic drive and not another vendors. FW is supposed to support up to 16 devices according to Apple so there is a huge disconnect. I do use several drives downstream from my 2nd Gen Drobo units, I mount/unmount religiously and have not had obvious problems with other drives.
    Having said that, I have not had another corruption problem since December 26 or so, but I also have not looked at every RAW file of the 40,000 stored on the Drobo. I figure I will find more, but will replace them as I find them.
    Regards, Steven

Maybe you are looking for

  • Excise problem in case of free items

    Hello, My user is having following issue. Vendor has sent 3 items, out of which one is free sample. But on that excise has to b paid by us (which is approx 3000rs). So when user is trying 2 do GR, first 2 items dont hav any problem, but after checkin

  • BROADBAND DROPPING OUT & APPLE MAC ISSUES....

    This is an ongoing problem for me. Today I spoke to a very well informed man who I sincerely hope has solved the problem. I had to connect computer to Home Hub with ethernet cable. He then talked me through re-start with a bent paper clip. Then told

  • Performance bottleneck with 2.2.1 and 2008 R2 os VM's

    Hi, I have DL370 g6 with Oracle vm server 2.2.1 installed *72 GB of Memory and 2 dual + quad core processor* All VM's are installed on local disk ( 6 300 GB in Raid 5 )* I have 2 nic connected to siwtch for lan traffic We have 10 VM's with 2008 R2 OS

  • Problems with changes in iOS5 Music app on iPad

    With iOS 5, massive changes have been made to the Music app that makes it virtually unusable for listening to podcasts.  Weirdly, these changes were not made on the iPhone version, which still works fine. My problems are these: 1.     Music App no lo

  • MacBook - right for me?

    Hello, I was wondering if any of you with MacBooks could help me out. I am trying to find out if the $1299 MacBook would be able to do what I need it to. I am huge on documentary-making and am about to upgrade to FinalCut Express. Would the $1299 Mac