(snippet) crazy fast image loading ...
in
Share your Work
•
3 years ago
hey all!
i recently needed to load images really really fast and access their pixel data.
so just in case anyone ever needs i'll post it here...
this allows you to load java bufferedimages, not processing's PImage.
most likely this will interrest you if you need to load lots of images and access their pixel data directly.
so far i've tested it on mac and windows with sun jvms, this might break if you use another vendors jvm.
so ultimately you'd use it like this:
BufferedImage img = loadImageCrazyFast( new File( "test.jpg" ).toURI().toURL() );
int pixels[] = loadPixelsCrazyFast( img );
img.flush(); // call this or you'll have memory leaks!
should be a good starting point if you ever need fast image loading...
i recently needed to load images really really fast and access their pixel data.
so just in case anyone ever needs i'll post it here...
this allows you to load java bufferedimages, not processing's PImage.
most likely this will interrest you if you need to load lots of images and access their pixel data directly.
so far i've tested it on mac and windows with sun jvms, this might break if you use another vendors jvm.
- /**
- * This is a bit of a hack and might change depending on which jdk you use!
- */
- public static BufferedImage loadImageCrazyFast( URL src ){
- try{
- Image im = Toolkit.getDefaultToolkit().createImage( src );
- Method method = im.getClass().getMethod( "getBufferedImage" );
- BufferedImage bim = null;
- int counter = 0;
- // load 30seconds maximum!
- while( bim == null && counter < 3000 ){
- im.getWidth( null );
- bim = (BufferedImage) method.invoke( im );
- try{ Thread.sleep( 10 ); }
- catch( InterruptedException e ){ }
- counter ++;
- }
- if( bim != null ){
- return bim;
- }
- }
- catch( Exception e ){
- System.err.println( "Fast loading of " + src.toString() + " failed. You might want to correct this in loadImageCrazyFast( URL )" );
- System.err.println( "Falling back to ImageIO, which is... slow!" );
- }
- try{
- return ImageIO.read( src );
- }
- catch( IOException ioe ){
- return null;
- }
- }
- /**
- * This is another bit of a hack and might also change
- */
- public static int[] loadPixelsCrazyFast( BufferedImage img ){
- return ((DataBufferInt) img.getRaster().getDataBuffer()).getData();
- }
so ultimately you'd use it like this:
BufferedImage img = loadImageCrazyFast( new File( "test.jpg" ).toURI().toURL() );
int pixels[] = loadPixelsCrazyFast( img );
img.flush(); // call this or you'll have memory leaks!
should be a good starting point if you ever need fast image loading...