Slow jpeg decoding?

Hi,
I have following problem. My program receives 10 per second (100ms) array of bytes that I muss decode to jpeg image (BufferedImage) and compare for differencies. BUT it's very slow. I tried many ways but results are still horrible.
    ByteArrayInputStream inA = new ByteArrayInputStream(a.data);
    JPEGImageDecoder decoderA = JPEGCodec.createJPEGDecoder(inA);
    Raster A = decoderA.decodeAsRaster();Only this decoding takes about 47ms !!! on my machine (MSI KT6V, Athlon 2600+ (overlocked over 2000MHz), 512MB...) Another way...
    ByteArrayInputStream inA = new ByteArrayInputStream(a.data);
    JPEGImageDecoder decoderA = JPEGCodec.createJPEGDecoder(inA);
    BufferedImage A = decoderA.decodeAsBufferedImage();It takes about 67ms. Anyone knows about faster solutions??? Please.
Thx in advance.

I have your problem. Have you got resolve it?

Similar Messages

  • JPEG decode: how to use it?

    Hello experts,
    I am using Labview 7 Express and Windows XP.
    I am downloading continuous datastreams of JPEG images from network cameras (Motion-JPEG streams, not MPEG).
    I use the TCP Read VI to get the streams, and I save them to disk on the fly. It works really great. I can also extract the JPEG files from the M-JPEG files on the fly, which works fine too. Now, I would like to display the JPEG images, using the JPEG Decode VI, but I am puzzled about how to do that: the output of the VI is a cluster of a string and a U32 number. What am I supposed to do with this number ? Is it a pointer?
    Thanks!
    Philippe

    Philippe,
    I am trying to do the exact same thing as you here: I have a network camera (Axis 206), and I am currently using 'URL Get HTTP Document.vi' to receive the stream og MJPG (multipart JPEG's). This works fine, but I have som problems displaying and compressing the images. At the end, logging data from a DAQ-card is supposed to be combined with the image stream into a single file.
    The 'IMAQ JPEG Decode.vi' is supposed to compress the images into a binary format. I have tried the setup you proposed, but any way I implement this vi the vi executes for less than a second and Labview shuts down.
    Any ideas what may be wrong? Displaying live JPEG's (not from a file) is obviously not something NI gave much thought.

  • Photoshop has problem with .JPEG decoding ??

    There seems to be an issue with either JPEG decoding in Photoshop or the blend modes don't work as they should. Or maybe someone finds the true reason ... ?
    Let's go step-by-step:
    This is the original image file (JPEG):
    This is the same image converted to .png:
    I examined the differences. Open one image and add the second image as a new layer over it with blend mode = difference. Use magic wand tool, with tolerance=zero. Expected results: entirely black image, entire image selected. Actual esults (white filled selection):
    [IMG]http://img372.imageshack.us/img372/694/differencepg1.png[/IMG]
    Merge both layers, invert the colors and you see the differences between the images. I applied a curves adjustment to exaggerate the differences:
    [IMG]http://img241.imageshack.us/img241/1995/difference2zw5.png[/IMG]
    Again, this time you should see an entirely white image, if both images were identical.
    The JPEG-to-PNG conversion was done with a third party image viewer that I trust. Obviously, the possibility exists, that this conversion is not exact/losless. But I can refute this, as I converted both the source JPEG image and the converted PNG image to BMP images, and the two files that were obtained this way were bit-for-bit identical:
    So it's impossible that any loss occured, given that in the a losless reconstruction was possible.
    Thus the error must be somewhere within Photoshop.
    Any ideas?

    There seems to be an issue with either JPEG decoding in Photoshop or the blend modes don't work as they should. Or maybe someone finds the true reason ... ?
    Let's go step-by-step:
    This is the original image file (JPEG):
    This is the same image converted to .png:
    I examined the differences. Open one image and add the second image as a new layer over it with blend mode = difference. Use magic wand tool, with tolerance=zero. Expected results: entirely black image, entire image selected. Actual esults (white filled selection):
    Merge both layers, invert the colors and you see the differences between the images. I applied a curves adjustment to exaggerate the differences:
    Again, this time you should see an entirely white image, if both images were identical.
    The JPEG-to-PNG conversion was done with a third party image viewer that I trust. Obviously, the possibility exists, that this conversion is not exact/losless. But I can refute this, as I converted both the source JPEG image and the converted PNG image to BMP images, and the two files that were obtained this way were bit-for-bit identical:
    So it's impossible that any loss occured, given that in the end a losless reconstruction was possible.
    Thus the error must be somewhere within Photoshop.
    Any ideas?

  • JPEG Decoder runtime error.

    Hi All,
    I want to build a jpegdecoder.swc because the library from http://code.google.com/p/as3-jpeg-decoder/downloads/list
    Has a memory leak.
    When I try to build with out making any changes and use the library it is throwing error.
    Step I followed:
    ===============================
    extracted   jpeg-6b.tar.gz
    ./configure
    make
    make test
    copied the main.c file to jpeg-6b directory
    alc-on;
    gcc main.c -O3 -Wall -swc -o jpegdecoder.swc
    WARNING: While resolving call to function 'main' arguments were dropped!
    3313.achacks.swf, 267843 bytes written
    frame rate: 60
    frame count: 1
    69 : 4
    72 : 267772
    76 : 34
    1 : 0
    0 : 0
    frame rate: 24
    frame count: 1
    69 : 4
    77 : 506
    64 : 31
    63 : 16
    65 : 4
    9 : 3
    41 : 26
    82 : 471
    1 : 0
    0 : 0
      adding: catalog.xml (deflated 75%)
      adding: library.swf (deflated 70%)
    And copied the jpegdecoder.swc to flex project.
    But when i run the project I am getting the below error
    =====================================
    Undefined sym: _jpeg_std_error
    at Function/<anonymous>()
    at Function/<anonymous>()
    at org.bytearray.decoder::JPEGDecoder/parse()[E:\chaitanya\WorkSpace_Flex_4\JpegDecodeTest_C ustom_JPEGLib\src\org\bytearray\decoder\JPEGDecoder.as:62]
    Please help me to solve the problem.
    Thanks in advance.

    Forget to attach the main.c file
    main.c
    =====================================================
    #include <stdio.h>
    #include "jpeglib.h"
    #include "cdjpeg.h"
    #include "AS3.h"
    #include <stdlib.h>
    int imageWidth;
    int imageHeight;
    int numComponents;
    int colorComponents;
    unsigned char *image;
    AS3_Val read_jpeg_file( char *filename )
    struct jpeg_decompress_struct cinfo;
    struct jpeg_error_mgr jerr;
    FILE *infile = fopen( filename, "rb" );
    if ( !infile )
    printf("Error opening jpeg file %s\n!", filename );
    return AS3_Int(-1);
    cinfo.err = jpeg_std_error( &jerr );
    jpeg_create_decompress( &cinfo );
    jpeg_stdio_src( &cinfo, infile );
    jpeg_read_header( &cinfo, TRUE );
    jpeg_start_decompress(&cinfo);
    // storing variables
    imageWidth = cinfo.image_width;
    imageHeight = cinfo.image_height;
    numComponents =  cinfo.num_components;
    colorComponents = cinfo.out_color_components;
    /* allocate data and read the image as RGBRGBRGBRGB */
    image = malloc(cinfo.output_width * cinfo.output_height * 3);
    int lng = cinfo.output_height;
    int i = 0;
    for(i=0; i < lng; i++)
    unsigned char * ptr = image + i * 3 * cinfo.output_width;
    jpeg_read_scanlines(&cinfo, &ptr, 1);
    (void) jpeg_finish_decompress(&cinfo);
    jpeg_destroy_decompress(&cinfo);
    return AS3_Int(1);
    static AS3_Val parseJPG( void *self, AS3_Val args )
    char * fileName;
    AS3_ArrayValue(args, "StrType", &fileName);
    read_jpeg_file( fileName );
    return AS3_Array("IntType, IntType, IntType, IntType, IntType", imageWidth, imageHeight, numComponents, colorComponents, (int)image);
    int main()
    AS3_Val parseJPGAlias = AS3_Function( NULL, parseJPG);
    AS3_Val result = AS3_Object( "parseJPG:AS3ValType", parseJPGAlias );
    AS3_Release( parseJPGAlias );
    AS3_LibInit( result );
    return 0;
    ============================================================

  • Time for jpeg decoding

    Hi to all!
    i'm working with a thread that read a stream from a camera (stream of Jpeg ) end show the video on the screen.
    I'm testing with max resolutions (704x576) e low compression at 25 fps.
    The result is very far from 25 fps! and depending from the library for decoding. I have tested with:
    1) immagine = ImageIO.read(test);
    2) immagine=Toolkit.getDefaultToolkit().createImage(imageData);
    3) with Reader: immagine = reader.read(0);
    4) with JPEGDecoder: immagine = decoderA.decodeAsBufferedImage();
    The target is 40 ms for one of that line.
    Analysing the problem i have found that the time for decoding Increases enormously every 3-4 frame (at 704x576 while at low resolutions the number increases) like:
    67 ms,70 ms,68 ms, 240 ms,68 ms,72 ms,77 ms,220 ms,69 ms,68 ms,77 ms,79 ms,199 ms,62 ms,59 ms, ecc..ecc...
    The size is consistently about 34000 byte (also when employs 200 ms....).
    and obviously average values of FPS collapse up to 3-6 fps (at 704x576) precisely those values up 200 ms !
    I can not understand why!
    that is for linux on pentium or for windows (java VM is version 6up5).
    No sleep or other operation is done at regular intervals that could cause this.
    Someone has had a similar problem or have a suggestion?
    thanks in advance,
    Nicola
    Edited by: nicopalm on Apr 10, 2008 2:07 AM
    Edited by: nicopalm on Apr 10, 2008 2:16 AM

    Thanks Andrew,
    I have tetsted your suggestion but i have some problem with my Reader ...
    i create imageinputstream for Reader from bytearrayinputstream and i must allocate a new test every time because the imagedata is different every time...
    test = new ByteArrayInputStream(bufferArray, 0,lungbyte);
    iis = ImageIO.createImageInputStream (test);
    I try to say as I did to find out if I have done well.....(sorry for my english...)
    1) I have a stream come from network camera.
    2) I open DataInputStream (iStrm).
    I know the lenght (L) of each image end i read from iStrm imageLength bytes (after i have fount the boundary e read the info between two images) .
    3) With these values fill a byte array (imageData). Because each images have different lenght, i must allocate imageData=new byte[imageLength]. (After draw i make imageData=null).
    4) With imageData i create a ByteArrayInputStream. test= new ByteArrayInputStream(imageData).
    5) Finally i have the multiple way to decode like image=ImageIO.read(test) or other....
    Is the proper procedure?
    My doubt is this:
    The new ByteArrayInputStream have the imageData like is buffer.
    Can i create a buffer of fixed size (example higher than the average value of images length)      so that i can make a new ByteArrayInputStream one time only ?
    In this way could fill the array (which is certainly less buffer).
    thanks
    Nicola

  • Garbage collector and JPEG decoder

    Hi,
    I have a problem with the garbage collector decoding JPEG images received on a TCP socket. The process works but each time that I have to decode an image I have to create a new decoder, this causes that the garbage collector starts to work constantly looking for memory. When the gc starts to work the streamed images almost stop since the gc takes all the process.
    Here is the code that has the problem. On this code you can see that I create a new ByteArrayInputStream and a MediaTracker, but I know how reuse this objets, the problem is on the decoder.
    Does any one have an idea of how to solve it?
    Thanks
    public void cargarImagen(Visualizador vision,
                                  Cabecera cabImg,
                                  boolean completa,
                                  boolean grabar,
                                  boolean pantCIF,
                                  JFrame1 jf1)throws Exception{
            Visualizador aux;
            ByteArrayInputStream byis = new ByteArrayInputStream(s1.buffer);
            try{
                    decoder=JPEGCodec.createJPEGDecoder(byis);
                    try{
                           // decode
                                                   vision.image_Webcam=decoder.decodeAsBufferedImage();
                    }catch(ImageFormatException b){
                      System.out.println("Incorrect image format");
                    }catch(Exception a){
                      System.out.println("Incorrect image");
                    mediaTracker_track = new MediaTracker(vision);
                    mediaTracker_track.addImage(vision.image_Webcam, 0);
                 mediaTracker_track.waitForID(0,500);
            }finally{
                      byis.close();
            if(mediaTracker_track.statusID(0, false) == MediaTracker.COMPLETE){
                  vision.repaint();
             else{    /* incorrect image */
                  vision.image_Webcam = null;
                  System.out.println("Discarded image");
    }

    I think that this is not the case. Images come from a TCP connection and the application start to read the next image from the socket when the previous one has been decoded and painted.
    So, images are not stored on memory and the received images rate depens on how fast is the application reading images from the socket.
    However, it is a good idea to start gc before getting next image, the average rate will decrease but it will avoid the "jumps" on visualization.

  • SUN JRE 1.3.1 slow JPEG file loading

    helo,
    I've developped an applet wich load jpeg files and display them on screen. I achieve my applet using Microsoft Java SDK 4.0 and all was fine. But my boss told me that the applet has to be run within the sun jre 1.3.1 plugin. When I test my applet with the sun plugin, it was horribly slow!!
    I wrote a little java app in order to compare the two jvm's. I establish that the Toolkit.getImage (+ media tracker for sync...) method was the main slowing point. I tested the app with 1.18 Mo jpeg files and found following results:
    Microsoft jvm : ~24 ms
    Sun JRE : ~250 ms
    about 10 times slower !!!
    What can I do??
    Am I stucked??
    thanx a lot
    cduret

    Kayaman, take a relax,
    there is no need to insult people. Many posts were written on this forum on "why do people get flamed for asking questions?". But there is no use to tell people they speak like 14 year old or they are from whatever UNI you mentioned in another post. At least don't forget that orher people also lose their time reading your answers. So if you have nothing to tell maybe just skip the topic.
    Mike

  • Jpeg decoding error

    I am doing a utility to generate thumbnail JPGs from normal sized of pictures.
    when I am decoding the encoded reduced image, I get an ImageFormatException....
    the exception message :
    sun.awt.image.ImageFormatException: Invalid JPEG file structure: missing SOS marker
    at sun.awt.image.JPEGImageDecoder.readImage(Native Method)
    at sun.awt.image.JPEGImageDecoder.produceImage(JPEGImageDecoder.java:144)
    at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:254)
    at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172)
    at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)
    My utility works when I tried to create NOT thumbnail JPGs(when the destination width and height bigger than 12)
    so what's worng?
    is a known bug?
    Tx in advance
    Orna

    Hi there,
    how are you loading the JPEGs? Probably loading them into a byte-array using getResourceAsStream()? If that's the case, go sure that the byte-array is big enough to hold all the data. Don't use InputStream.available(), unless you load the data in several chunks.
    Kind regards,
    Arno Huetter

  • Jpeg decoding

    Does anyone know if there is a Java version of the libjpeg libraries or something similar? I need to take in jpeg data and generateraw 8 bit colour pixel data.
    Cheers
    Jeremy

    Try to use standard jpeg encoder/decoder that included in J2SDK:
    com.sun.image.codec.jpeg package.
    I hope it will help you.
    Sincerely,
    Victor Letunovsky
    AlarIT programmer
    http://www.AlarIT.com

  • Nikon Jpeg decoding problem.

    Jpeg files saved with the ICC profile "Nikon sRGB 4.0.0.3001" by Nikon PictureProject do not load properly using Java ImageIO.read(). The image is far too dark, but the colors are not swapped.
    This appears to be similar to the problems reported in bugid 6246622, which was fixed in 1.5_04 and is now closed.
    I tested this using Java version 1.5.0_06. The following code provides a workaround
        ImageInputStream iis = ImageIO.createImageInputStream(file);
        Iterator<ImageReader> iir = ImageIO.getImageReaders(iis);
        boolean looking = true;
        ImageReader reader = null;
        ImageReadParam param = null;
        while(looking && iir.hasNext()) {
            reader = iir.next();
            reader.setInput(iis);
            param = reader.getDefaultReadParam();
            Iterator it = reader.getImageTypes(0);
            while (looking && it.hasNext()) {
                ImageTypeSpecifier type = (ImageTypeSpecifier) it.next();
                ColorSpace cs = type.getColorModel().getColorSpace();
                if ( cs.isCS_sRGB() ) {
                    param.setDestinationType(type);
                    looking = false;
                if ( cs.getType() != ColorSpace.TYPE_RGB ) {
                    looking = false;
        if (reader != null) {
            img = reader.read(0, param);
        }Does anyone have a better workaround for this other than using Toolkit or Applet.
    I will file this as a bug report, but the Bug Database is not responding at present.

    Sun has assigned this a bug id
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6372769

  • JNI call seem to be very slow

    Hello,
    I have an optimized JPEG decoder written in C++, I have a JNI bridge to that codebase with this method:
    Java-side:
    public static native byte[] readJPEG(String name);C++ side:
    JNIEXPORT const jbyteArray JNICALL Java_IPPJPEGDecoder_readJPEG(JNIEnv *, jclass, jstring);I have this call in Java layer:
    long start = System.currentTimeMillis();
    byte[] data = IPPJPEGDecoder.readJPEG("C:\\D-102_red_ink_1.JPG");
    long end = System.currentTimeMillis();
    System.out.println("total time = " + (end - start));This is my method in C++ (rough/ugly code, don't judge me :) )
    JNIEXPORT const jbyteArray JNICALL Java_IPPJPEGDecoder_readJPEG (JNIEnv * env, jclass jobj, jstring jpeg_filename)
        //cout << "INVOKED IPPJPEGDecoder.readJPEG() SUCCESSFULL" << endl;
        //cout << "Started"<<endl;
        CIppImage m_image;
        CIppImage grayscale_image;
        CIppImage monochrome_image;
        CTimer timer;
        timer.Start();
        CStdFileInput in;
        const IppLibraryVersion* libver = ippGetLibVersion();
        cout << "LibraryVersion = (" << libver->Name <<": " << libver->Version << ")"<<endl;
        UIC::BaseStream::TStatus status;
        jboolean iscopy;
        const char * filename = env->GetStringUTFChars(jpeg_filename,&iscopy);
        status = in.Open(filename);
        GetImageFromJPEGJNI(in, m_image, timer);
        cout<<"m_image: (Precision: " << m_image.Precision() << ", NumChannels: " <<m_image.NChannels()<<", Width: " << m_image.Width() << ", Height: " << m_image.Height()<< ", Color: " << m_image.Color() <<", step: " << m_image.Step()<<endl;
        timer.Start();
        cout << "data array size of image : " <<(m_image.Step()*m_image.Height())<<endl;
        jbyteArray jb = env->NewByteArray(m_image.Step()*m_image.Height());
        env->SetByteArrayRegion(jb,0, m_image.Step()*m_image.Height(),(const jbyte*)m_image.DataPtr());
        timer.Stop();
        double mytime = timer.GetTime();
        cout << "JNI occurred in " << mytime << " ms"<<endl;
        return jb;
        //return NULL;
    }When I call this code, the C++ codeblock reports as running in 92.7793 ms
    My java code reports back: 572 ms
    is the Call to the JNI method THAT INSANELY slow !?!?! I MUST be doing something wrong... this is in Windows XP and I'm linking against my own dll that I compiled in Microsoft Visual C++ 2008.
    The jbyteArray that I'm passing back has a length of 33583500
    ... maybe it's the conversion from jbyteArray to Java's byte[] that is causing all the overhead.... are there any ways around that?
    Thanks!!
    Alessandro Ferrucci

    alessandro_ferrucci wrote:
    I need to process about *500 MILLION* images...this speed difference matters So at 1 second per image it will take 16 years. Or with 100 machines 2 months.
    JNI Code completes in 337 ms (still about 200 ms faster than ImageIO's libjpeg on my machine),So now you are down to 5 years. Or 20 days with 100 machines.
    Course all of the above is 24x7 dedicated processing.
    If it was me I would look into changing the requirements and the architecture.
    Probably cost effective to hire several senior level programmers with experience in image processing and/or performance optimization as well.

  • GIF decoding from stream

    In the table are stored GIF and JPEG images, which can be edited by the user, and then to be written back. Here the code, which handles JPEG-images:
    OraclePreparedStatement pstmt = (OraclePreparedStatement) conn.prepareStatement (
    " SELECT mime _ type, content FROM wwv _ document $ WHERE name =? "
    Pstmt.setString (1, sourceImage);
    OracleResultSet rs = (OracleResultSet) pstmt.executeQuery ();
    If (rs.next ()) {
    String imageType = rs.getString (1);
    If (imageType.endsWith (" jpeg ")) {// decoding jpeg image
    InputStream in = rs.getBinaryStream (2);
    ByteArrayOutputStream out = new ByteArrayOutputStream ();
    JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder (in);
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder (out);
    BufferedImage sourceImg = decoder.decodeAsBufferedImage ();
    // Processing an image
    BufferedImage img=makeSomeWork(sourceImg);
    encoder.encode (img);
    // Recording an image
    Question: that it is necessary to write instead of lines
    JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder (in);
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder (out);
    to work with GIF-images?
    Thanks.

    hi,
    there is Java Advance Imaging JAI which can do a lot more for graphic.
    JAI Home page http://java.sun.com/products/java-media/jai/index.html
    here are jars :
    c:\jdk\lib\jai_codec.jar;
    c:\jdk\lib\jai_core.jar;
    c:\jdk\lib\mlibwrapper_jai.jar
    here is example demo from JAI demos.
    * @(#)FormatDemo.java     12.2 01/09/21
    * Copyright (c) 2001 Sun Microsystems, Inc. All Rights Reserved.
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions are met:
    * -Redistributions of source code must retain the above copyright notice, this
    * list of conditions and the following disclaimer.
    * -Redistribution in binary form must reproduct the above copyright notice,
    * this list of conditions and the following disclaimer in the documentation
    * and/or other materials provided with the distribution.
    * Neither the name of Sun Microsystems, Inc. or the names of contributors may
    * be used to endorse or promote products derived from this software without
    * specific prior written permission.
    * This software is provided "AS IS," without a warranty of any kind. ALL
    * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
    * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
    * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
    * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
    * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
    * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
    * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
    * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
    * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
    * POSSIBILITY OF SUCH DAMAGES.
    * You acknowledge that Software is not designed,licensed or intended for use in
    * the design, construction, operation or maintenance of any nuclear facility.
    import com.sun.media.jai.codec.FileSeekableStream;
    import com.sun.media.jai.codec.ImageCodec;
    import com.sun.media.jai.codec.SeekableStream;
    public class FormatDemo {
    public static void main(String[] args) {
    if (args.length < 1) {
    System.out.println(
    "Format recognizer demo:\n");
    System.out.println(
    " Given a file, determine which file formats it may be encoded in.");
    System.out.println(
    " In addition to the standard formats, a \"samplepnm\" codec is");
    System.out.println(
    " registered.\n");
    System.out.println("usage: java FormatDemo <filenames>");
    System.exit(0);
    // Register the sample PNM codec
    ImageCodec.registerCodec(new SamplePNMCodec());
    try {
    for (int i = 0; i < args.length; i++) {
    SeekableStream stream = new FileSeekableStream(args);
    String[] names = ImageCodec.getDecoderNames(stream);
    System.out.println("File " +
    args[i] +
    " may be in the following format(s):");
    for (int j = 0; j < names.length; j++) {
    System.out.println("\t" + names[j]);
    System.out.println();
    } catch (Exception e) {
    e.printStackTrace();
    here is the required helper class to run the above program.
    * @(#)SamplePNMCodec.java     12.2 01/09/21
    * Copyright (c) 2001 Sun Microsystems, Inc. All Rights Reserved.
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions are met:
    * -Redistributions of source code must retain the above copyright notice, this
    * list of conditions and the following disclaimer.
    * -Redistribution in binary form must reproduct the above copyright notice,
    * this list of conditions and the following disclaimer in the documentation
    * and/or other materials provided with the distribution.
    * Neither the name of Sun Microsystems, Inc. or the names of contributors may
    * be used to endorse or promote products derived from this software without
    * specific prior written permission.
    * This software is provided "AS IS," without a warranty of any kind. ALL
    * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
    * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
    * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
    * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
    * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
    * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
    * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
    * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
    * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
    * POSSIBILITY OF SUCH DAMAGES.
    * You acknowledge that Software is not designed,licensed or intended for use in
    * the design, construction, operation or maintenance of any nuclear facility.
    import java.awt.image.DataBuffer;
    import java.awt.image.RenderedImage;
    import java.awt.image.SampleModel;
    import java.io.BufferedInputStream;
    import java.io.InputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import com.sun.media.jai.codec.ForwardSeekableStream;
    import com.sun.media.jai.codec.ImageCodec;
    import com.sun.media.jai.codec.ImageDecoder;
    import com.sun.media.jai.codec.ImageDecodeParam;
    import com.sun.media.jai.codec.ImageEncoder;
    import com.sun.media.jai.codec.ImageEncodeParam;
    import com.sun.media.jai.codec.PNMEncodeParam;
    import com.sun.media.jai.codec.SeekableStream;
    * A subclass of <code>ImageCodec</code> that handles the
    * PNM family of formats (PBM, PGM, PPM).
    * <p> The PBM format encodes a single-banded, 1-bit image. The PGM
    * format encodes a single-banded image of any bit depth between 1 and
    * 32. The PPM format encodes three-banded images of any bit depth
    * between 1 and 32. All formats have an ASCII and a raw
    * representation.
    public final class SamplePNMCodec extends ImageCodec {
    /** Constructs an instance of <code>SamplePNMCodec</code>. */
    public SamplePNMCodec() {}
    /** Returns the name of the format handled by this codec. */
    public String getFormatName() {
    return "samplepnm";
    /** Returns <code>null</code> since no encoder exists. */
    public Class getEncodeParamClass() {
    return null;
    * Returns <code>Object.class</code> since no DecodeParam
    * object is required for decoding.
    public Class getDecodeParamClass() {
    return Object.class;
    /** Returns true if the image is encodable by this codec. */
    public boolean canEncodeImage(RenderedImage im,
    ImageEncodeParam param) {
    SampleModel sampleModel = im.getSampleModel();
    int dataType = sampleModel.getTransferType();
    if ((dataType == DataBuffer.TYPE_FLOAT) ||
    (dataType == DataBuffer.TYPE_DOUBLE)) {
    return false;
    int numBands = sampleModel.getNumBands();
    if (numBands != 1 && numBands != 3) {
    return false;
    return true;
    * Instantiates a <code>PNMImageEncoder</code> to write to the
    * given <code>OutputStream</code>.
    * @param dst the <code>OutputStream</code> to write to.
    * @param param an instance of <code>PNMEncodeParam</code> used to
    * control the encoding process, or <code>null</code>. A
    * <code>ClassCastException</code> will be thrown if
    * <code>param</code> is non-null but not an instance of
    * <code>PNMEncodeParam</code>.
    protected ImageEncoder createImageEncoder(OutputStream dst,
    ImageEncodeParam param) {
    PNMEncodeParam p = null;
    if (param != null) {
    p = (PNMEncodeParam)param; // May throw a ClassCast exception
    return new SamplePNMImageEncoder(dst, p);
    * Instantiates a <code>PNMImageDecoder</code> to read from the
    * given <code>InputStream</code>.
    * <p> By overriding this method, <code>PNMCodec</code> is able to
    * ensure that a <code>ForwardSeekableStream</code> is used to
    * wrap the source <code>InputStream</code> instead of the a
    * general (and more expensive) subclass of
    * <code>SeekableStream</code>. Since the PNM decoder does not
    * require the ability to seek backwards in its input, this allows
    * for greater efficiency.
    * @param src the <code>InputStream</code> to read from.
    * @param param an instance of <code>ImageDecodeParam</code> used to
    * control the decoding process, or <code>null</code>.
    * This parameter is ignored by this class.
    protected ImageDecoder createImageDecoder(InputStream src,
    ImageDecodeParam param) {
    // Add buffering for efficiency
    if (!(src instanceof BufferedInputStream)) {
    src = new BufferedInputStream(src);
    return new SamplePNMImageDecoder(new ForwardSeekableStream(src), null);
    * Instantiates a <code>PNMImageDecoder</code> to read from the
    * given <code>SeekableStream</code>.
    * @param src the <code>SeekableStream</code> to read from.
    * @param param an instance of <code>ImageDecodeParam</code> used to
    * control the decoding process, or <code>null</code>.
    * This parameter is ignored by this class.
    protected ImageDecoder createImageDecoder(SeekableStream src,
    ImageDecodeParam param) {
    return new SamplePNMImageDecoder(src, null);
    * Returns the number of bytes from the beginning of the data required
    * to recognize it as being in PNM format.
    public int getNumHeaderBytes() {
    return 2;
    * Returns <code>true</code> if the header bytes indicate PNM format.
    * @param header an array of bytes containing the initial bytes of the
    * input data. */
    public boolean isFormatRecognized(byte[] header) {
    return ((header[0] == 'P') &&
    (header[1] >= '1') &&
    (header[1] <= '6'));

  • DECODE OR CASE - Which is better and why

    Oracle version: 11.2
    Problem: We have a huge table with 10M records, which needs to be processed daily.
    While loading data in table we have to handle condition if flag is =1 then '111' else '000'
    To implement this which one is efficient solution? .. using CASE or DECODE and why?
    Example:
    SQL> select flag,case when flag='Y' then '111' else '000' end from (select 'Y' as flag from dual union all select 'N' from dual);
    F CAS
    Y 111
    N 000
    SQL> select flag,decode(flag,'Y','111','000') from (select 'Y' as flag from dual union all select 'N' from dual);
    F DEC
    Y 111
    N 000

    Hi,
    For this job, they're equally efficient.
    For any job, where DECODE doesn't require a lot more code than CASE, they will be equally efficient.
    I recommend (almost) always using CASE. It's easier to understand and debug, and, if written correctly, will never be slower than DECODE.
    The only situation where I use DECODE is for very simple tasks (like the one you posted) where this is used inside a very complicated expression, and the slightly less coding needed for DECODE makes the larger statement easier to read.

  • Jpeg images in midlets

    I need to read a jpeg file and make a usable Image object from it. The jpeg "decoding" must be done in the midlet since I will use it in an applications for watching live images from network cameras on my phone.
    I know there are a few image viewers available that support jpeg, so it can not be impossible to implement, but I can't find any usable help on the different forums I have searched.
    I know it isn't going to be very fast doing the decoding on the phone, but speed is not that important.

    Go to Wotsit, learn all you can about the jpeg format, and write a decoder.
    shmoove

  • Converting JPEG to BufferedImage using previously allocated BufferedImage

    I have an application containing 11 Thumbnails fed by streams of JPEG images at 5 fps and a large panel that shows the image full size. Each thumbnail and the large panel are separate applets in a web page. The jpeg images are received directly into a byte array (byte[]) which is wrapped with a byte buffer. The images are then displayed using a jpeg reader which produces a new BufferedImage which is drawn using the awt graphics object drawImage method.
    The application works great except that the image io library always allocates a new BufferedImage for each conversion. This creates a huge swing in memory use and on some "busier" or less powerful clients, the mark and sweep garbage collection sometimes does not get run often enough to prevent memory use from getting rather huge, even if I call System.gc() on a regular basis. The overall effect is that the amount of JVM memory goes through some pretty big swings and after enough of these swings, the application starts to bog down. Note that there is no actual leak: the swings return to a memory allocation level that does not grow with time, and it always hits this level after the mark and sweep.
    To try to get this under control, I'd like to see if I can get a jpeg decoder that will write to an existing buffered image and its corresponding raster to avoid allocating a brand new RGB image for each frame. Is there any way to construct an image decoder for jpeg to awt renderable images that knows how to recycle existing BufferedImage/Raster objects?????
    Thanks,
    Paul

    1. Get an image reader using ImageIO.getImageReadersByFormatName.
    2. Use ImageReadParam and specify your existing BufferedImage as destination using readAsRenderedImage.

Maybe you are looking for

  • "safari quit unexpectedly" on opening everytime (lion)

    I have been having problems with safari.  It will not open and continues to give me the message "safari quit unexpectedly" I have tried various things including reinstalls.  When I reinstall it the program will work for a day or two then the same mee

  • ISync no longer works with MacBook

    I imported all data from my old Powerbook G4 into my new Intel MacBook 2.16 bu iSync no longer works with my phones. It starts the process then stops abut halfway through with an error message. I have tried all the solutions proposed in the discussio

  • Problems combining 2 pages into 1

    OK, we have our department letterhead as a .pdf file (created in MS Office and saved as .pdf) and we have a fillable fax coversheet form created in Adobe Acrobat 9.0 and LiveCycle Designer and saved as a .pdf.  We need to combine these two into one d

  • T510 - Error 0210: Stuck key 45

    I get the message "Erro 0201: Stuck key 45" and then <Press F1>. I hit an Esc and login but, have keying problems with typing when the laptop is connected to the dock = mouse's first button does not show the menu;  if i press shift button i don't get

  • Integration of Demantra 7.3 with JDE 9.0

    Hi All, Plz can some one guide me to integrate standalone Demantra 7.3 with JDE 9.0 and integration of VCP 12.1 with JDE 9.0. Plz let me know what is the pre requisites for this Regards Sajid