Reading a JPEG as a byte array.

Hello everyone.
I am developing a project which involves using JPEG images with Java. I would like to use the java.awt.Image class but there's a snag:
I am reading the file in as a byte array and then need to pass the bytes to an object to be displayed as an image. "why not just read it as a normal JPEG file in the first place?!" I hear you say. Yes, this would be easier but there is a good reason as to why I am reading as a byte array first and this cannot be worked around.
If anyone has some suggestions I'd very much like to hear them.
All the best,
P.M.

If all you're going to do is display the image, then you can use Toolkit#createImage(byte[] imagedata). That's about as direct as you can get. If you plan on manipulating the images in any way, though, then as above post says ByteArrayInputStream + ImageIO is the way to go.
"why not just read it as a normal JPEG file in the first place?!" I hear you say. Yes, this would be easier but there is a good reason as to why I am reading as a byte array first and this cannot be worked around.Fun fact: For the ImageIO package, reading from the file is actually faster than reading from an InputStream that references the file's contents as a byte[] array. Specifically, the ImageInputStream implementation that wraps the file is faster then the one that wraps a generic InputStream.

Similar Messages

  • How do I read directly from file into byte array

    I am reading an image from a file into a BuffertedImage then writing it out again into an array of bytes which I store and use later on in the program. Currently Im doing this in two stages is there a way to do it it one go to speed things up.
    try
                //Read File Contents into a Buffered Image
                /** BUG 4705399: There was a problem with some jpegs taking ages to load turns out to be
                 * (at least partially) a problem with non-standard colour models, which is why we set the
                 * destination colour model. The side effect should be standard colour model in subsequent reading.
                BufferedImage bi = null;
                ImageReader ir = null;
                ImageInputStream stream =  ImageIO.createImageInputStream(new File(path));
                final Iterator i = ImageIO.getImageReaders(stream);
                if (i.hasNext())
                    ir = (ImageReader) i.next();
                    ir.setInput(stream);
                    ImageReadParam param = ir.getDefaultReadParam();
                    ImageTypeSpecifier typeToUse = null;
                    for (Iterator i2 = ir.getImageTypes(0); i2.hasNext();)
                        ImageTypeSpecifier type = (ImageTypeSpecifier) i2.next();
                        if (type.getColorModel().getColorSpace().isCS_sRGB())
                            typeToUse = type;
                    if (typeToUse != null)
                        param.setDestinationType(typeToUse);
                    bi = ir.read(0, param);
                    //ir.dispose(); seem to reference this in write
                    //stream.close();
                //Write Buffered Image to Byte ArrayOutput Stream
                if (bi != null)
                    //Convert to byte array
                    final ByteArrayOutputStream output = new ByteArrayOutputStream();
                    //Try and find corresponding writer for reader but if not possible
                    //we use JPG (which is always installed) instead.
                    final ImageWriter iw = ImageIO.getImageWriter(ir);
                    if (iw != null)
                        if (ImageIO.write(bi, ir.getFormatName(), new DataOutputStream(output)) == false)
                            MainWindow.logger.warning("Unable to Write Image");
                    else
                        if (ImageIO.write(bi, "JPG", new DataOutputStream(output)) == false)
                            MainWindow.logger.warning("Warning Unable to Write Image as JPEG");
                    //Add to image list
                    final byte[] imageData = output.toByteArray();
                    Images.addImage(imageData);
                  

    If you don't need to manipulate the image in any way I would suggest you just read the image file directly into a byte array (without ImageReader) and then create the BufferedImage from that byte array.

  • How to Read a File into a Byte Array??

    I want to make an array of data objects that works as a byffer to write from a file to another file
    do you have any sygestions?

    The way I would do it (if I dont misunderstand your question) is to use FileInputStream to pass in the streaming data source.
    then read the file source to a list object. For example, LikedList.
    then tell the LikedList to transcribe itself to an array of any type, in this case, byte.

  • How to load and display a byte array (jpeg) image file dynamically in Flex?

    My web service client (servlet) received a binary jpeg data from an Image Server. The Flex application invokes the
    servlet via HttpService and receives the binary jpeg data as byte array.  How could it be displayed dynamically
    without writing the byte array to a jpeg file?  Please help (some sample code is very much appreciated).

    JPEGEncoder is only useful for converting BitmapData to ByteArray, not the other way around.
    By the way JPEGEncoder and PNGEncoder are part of the Flex SDK now, so no need to use AS3Lib (alltough it's a good library to have around).
    To display/use a ByteArray as image, use a Loader instance with the loadBytes method.
        Loader.loadBytes(bytes:ByteArray, context:LoaderContext = null);
    Listen for the complete event on the Loader.contentLoaderInfo and get the BitmapData in the event handler.
    private function loadJpeg():void {
        var loader:Loader = new Loader();
        loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderCompleteHandler);
        //jpgBA is the ByteArray loaded from webservice
        loader.loadBytes(jpgBA);
    private function loaderCompleteHandler(evt:Event):void {
        var t:LoaderInfo = evt.currentTarget as LoaderInfo;
        // display the jpeg in an Image component
        img.source = t.content;
    <mx:Image id="img" scaleContent="false" />

  • Issue with reading byte array

    I have a binary file to be read.I want to read the whole file into a byte array. But while doing so the values which are greater than 128 are read as negative values as we have Signedbyte in java(-127 to 128).
    So I tried reading the bytes into the int array as shown in the below code.
    int i = 0;
         int content[]= new int[(int)size];
         FileInputStream fstream = new FileInputStream(fileName);
         DataInputStream in = new DataInputStream(fstream);
         while(i<size)
         content= in.readUnsignedByte();
         i++;
    The above function 'readUnsignedByte();' reads byte and stores it into an int array.....But since the file contains around 34000 bytes ....the loop runs 340000 times .....which is a performance hazard.
    After googling for hours ....I could still not find any alternative ....
    I want to read byte and want to store in int array but instead of loop, I want to read the file at once.
    Or is there any way to implement Unsigned Byte in java so that I can read the entire file in byte array without corrupting the values which are greater than 128..
    I have to deliver the code asap .....Please help me out with an alternative solution for this...
    Thanks in advance....

    Thanks for replying ......
    Actually, I need to take the bytes into an array(int or byte array) with decimal values and further process these decimal values.......
    but while reading the file into a byte array the decimal values get corrupted(in case when I read a number greater than 128) but in this case I am able to read the whole file at once(without using any loop) as done by the following code
         FileInputStream fstream = new FileInputStream(fileName);
         DataInputStream in = new DataInputStream(fstream);
         byte b[] = null;
         in.readFully(b);
    and while reading the file in int array as done in the below code is inefficient as the number of times the loop runs is more than 34000..... please suggest me some alternative.
    int i = 0;
         int content[]= new int[(int)size];
         FileInputStream fstream = new FileInputStream(fileName);     
         DataInputStream in = new DataInputStream(fstream);
         while(i<size)
                   content= in.readUnsignedByte();
                   i++;

  • Is there a memory limitation to byte arrays?

    Everyone,
    I have a huge(16MB) CMYK source file and I am trying to convert it to a sRGB /JPEG file and then compress it.
    When I try to read that file into a byte array it chokes and throws an OutOfMemoryException. Is there a way around this?
    thanks,
    Barat.

    The data looks something like this:
    CCCCC...MMMMM...YYYYY...KKKKK...
    CCCCC...MMMMM...YYYYY...KKKKK...
    where each letter represents one byte.
    For example, the first cyan byte has cyan information
    for 8 pixels -- each bit represents cyan or no cyan, etc.
    The point is to get this data in a viewable form on screen.
    Have tried increasing the heap to 256
    Of course the problem is in a large array that holds the output information, which is ~130M
    The original file size is 16M but this was expanded to eight times the size for the PixelInterleavedSampleModel
    where one data element (a byte in this case) represents one sample of a pixel
    There must be a better way - any suggestions?

  • Play flv byte array in Air Application

    I'm trying to load and play an FLV from a ByteArray in Air application . I have created small dummy application in  which l am readiong flv from file system .After reading flv file i have byte array so can you please help me out in thi how to p-lay flv from byte array.
    I have searched the web for awnsers and didn't find anything .
    Any help, ideas or something?

    Hi Giuseppe,
    what I do is:
    1. create a file using Captivate
    2. i place a .flv video in this file
    3. save the file as .swf
    4. then i go to dreamweaver and put the swf on a html page.
    Now:
    when viewed in a browser, everything runs fine.
    when i pack this page into an air application (in dreamweaver) the video does not appear,
    instead I get this "Connection Error"
    I do not know a console or log file.
    However, I learned that there is a .xml file located in the same AIR folder that you publish in.
    In this .xml file there is a setting :transparency. in order to playt a .flv file this must not be be "transparent"!
    (i read this somewhere in the net)
    hope that helps
    I will talk to a professional programmer, if I have any news, i will let you know
    Claus

  • Display byte array of jpeg  in jsp

    I have a byte array of jpeg image in my jsp. Now I want to display it in my image. I tried but i could not see the image but a red mark image is comming on the screeen
    Please help me out. I deadly help need ASAP. Thanks in advance.
    this is how i tried
    response.setContentType("image/jpeg");
    ServletOutputStream os = response.getOutputStream();
    // i get byte array from loDocumentDVO.getFileContents():
    byte[] fileContent = loDocumentDVO.getFileContents();
    os.write(fileContent);
    os.flush();

    Thank you for your sharp words.
    I have now compiled the ImageServlet I have adapted slightly from http://balusc.xs4all.nl/srv/dev-jep-img.html
    I am trying to run it with
    <html>
    <body>
    <img src="image?file=plan.jpg" alt="Plan" />
    </body>
    </html>
    but all that is displayed is the word Plan.
    My servlet has been compiled and put into webapps\test\classes\example directory.
    My web.xml contains
    <servlet>
    <servlet-name>ImageServlet</servlet-name>
    <servlet-class>example.ImageServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>ImageServlet</servlet-name>
    <url-pattern>/image/*</url-pattern>
    </servlet-mapping>
    The servlet code is
    package example;
    import java.io.*;
    import java.net.URLConnection;
    import javax.servlet.*;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class ImageServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
            String imageFilePath = getServletContext().getRealPath("/WEB-INF/images");
            // Get file name from request.
            String imageFileName = request.getParameter("file");
         System.out.println("Path: "+imageFilePath+" Name: "+imageFileName);
            // Check if file name is supplied to the request.
            if (imageFileName != null) {
                // Strip "../" and "..\" (avoid directory sniffing by hackers!).
                imageFileName = imageFileName.replaceAll("\\.+(\\\\|/)", "");
            } else {
                return;
            // Prepare file object.
            File imageFile = new File(imageFilePath, imageFileName);
            // Check if file actually exists in filesystem.
            if (!imageFile.exists()) {
                return;
            // Get content type by filename.
            String contentType = URLConnection.guessContentTypeFromName(imageFileName);
            // Check if file is actually an image (avoid download of other files by hackers!).
            // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
            if (contentType == null || !contentType.startsWith("image")) {
                return;
            // Prepare streams.
            BufferedInputStream input = null;
            BufferedOutputStream output = null;
            try {
                // Open image file.
                input = new BufferedInputStream(new FileInputStream(imageFile));
                int contentLength = input.available();
                // Init servlet response.
                response.reset();
                response.setContentLength(contentLength);
                response.setContentType(contentType);
                response.setHeader(
                    "Content-disposition", "inline; filename=\"" + imageFileName + "\"");
                output = new BufferedOutputStream(response.getOutputStream());
                // Write file contents to response.
                while (contentLength-- > 0) {
                    output.write(input.read());
                // Finalize task.
                output.flush();
            } catch (IOException e) {
                // Something went wrong?
                e.printStackTrace();
            } finally {
                // Gently close streams.
                if (input != null) {
                    try {
                        input.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        // This is a serious error. Do more than just printing a trace.
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        // This is a serious error. Do more than just printing a trace.
    }The servlet isn't being called - nothing is output to my server log file. Changing the name of my servlet doesn't change the result.
    I can't see why the servlet isn't being called.
    I have built another simple servlet that does work so I know my server is OK.
    Any suggestions?
    Thanks,
    David

  • How to save Byte Array of raw data into JPEG image.

    Hello!
    I have a image and I stored its data as byte array as
    bimage = bitmap1.getRawData();
    now I have Byte[] bimage, I want to save it as .jpeg image.
    and show that image..............

    the short way is this:
    ImageIO.write(bimage, "jpeg", new File("image.jpg"));
    Where you use the original Image object... but it has to be a java.awt.image.RenderedImage (which a java.awt.image.BufferedImage is). So this method would come in handy.
         public static BufferedImage getBufferedImage(Image img) {
              // if the image is already a BufferedImage, cast and return it
              if((img instanceof BufferedImage) && background == null) {
                   return (BufferedImage)img;
              // otherwise, create a new BufferedImage and draw the original
              // image on it
              int w = img.getWidth(null);
              int h = img.getHeight(null);
              BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g2d = bi.createGraphics();
              g2d.drawImage(img, 0, 0, w, h, null);
              g2d.dispose();
              return bi;
         }If the byte array you have is raw image data, then you can look at the javax.imageio package and see what you can do with those classes.

  • Change quality of JPEG byte array

    I have a JPEG file which I read into a byte array in my program, the problem is that I need to change the quality of this image, is it possible? If so, how?

    i think these two links could help you:
    [JAI cookbook|http://www.lac.inpe.br/~rafael.santos/JIPCookbook/6040-howto-compressimages.jsp]
    [java.sun.com|http://java.sun.com/products/java-media/jai/forDevelopers/jai1_0_1guide-unc/Encode.doc.html#51423]

  • Display jpeg byte array with JSP !!

    I am new in JSP area so maybe I ask a easy question !!
    First, on the server side:I use a C++ program to stream sequence jpeg data out(FF D8 ~ FF D9).
    Second, on the client side:I use jsp to open a socket and read
    data to a byte array.
    Can anyone tell me how to display the jpeg array on browser one by one ?

    um... like video frames, or just a single image? I wouldn't really use JSP for that, I'd use a servlet, set the content-type to image/jpeg and just write out the bytes. Unless you are talking about displaying the bytes themselves, in which case, a JSP page would be better. If it's video frames, I'm not sure how to have the browser do that, since most no longer support server push.

  • Reading camera's DevieInfo NOT in byte array?!

    Hello everyone,
    I am struggling to retrieve a DeviceInfo dataset from a camera that I have.
    At first I thought it will be easy, something like:
    OSErr err;
    ICACopyObjectPropertyDictionaryPB dictPB = {};
    NSDictionary* deviceDict = NULL;
    dictPB.object = [[[self leCamera] cameraID] unsignedLongValue];
    dictPB.theDict = (CFDictionaryRef*)(&deviceDict);
    err = ICACopyObjectPropertyDictionary(&dictPB, NULL);
    if (err == noErr)
    [[self window] setTitle: [deviceDict objectForKey: @"device firmware"]];
    The problem is the firmware version is not in the dictionary that I get with
    the ICACopyObjectPropertyDictionary command and yes I have the right
    deviceID(cameraID).
    The second thing that I have tried is to retrieve the object with PTPPassThru
    command which works and the firmaware is there but I get like 256 bytes
    buffer which is really tedious to work with(the problem is that there are
    variable fields in this buffer and I have to read their size every time in order
    to jump over certain number of bytes in which I am not interested.).
    So the questions that occur to me are, am I the first one who needs to do
    such a thing? I guess not. How did the guys before me accomplish it? Is
    the PTPPassThru command and the buffer processing the only way to go
    or is there some ICA function returning a dictionary with what I need.
    Any help or insights will be greatly appreciated!
    Best regards
    artOf...

    I took the hard way and retrieved the information that I needed as byte array...
    The application is functioning now, anyway if anyone has some suggestions
    they are all welcome.
    Regards
    artOf...

  • How to open a byte array of pdf into acrobat reader dynamically..

    hi,
    my java program is connecting to a url and downloading various file(.pdf,.xml format) into hard-disk. now the requirement is if user select "Preview" button, then file is downloaded and opened with appropriate application(acrobat reader for .pdf file) but not saved anywhere in hard-disk ...
    any idea, any hint any help is welcomed..
    thanks in advance..

    hi friends,
    i got the solution. i am using one external api of adobe acrobat, through which i am able to stream pdf document in form of byte array into acrobat viewer,without writing data in any file.
    so my work is done.. :)

  • Problem in reading/writing byte array in Access database! PLEASE HELP!!

    Hi,
    I want to store a signature, which is in form of a byte array, in OLE Object field in MS Access database. I want then to retrieve this signature and verify it. The problem is that the retrieved byte array is not identical to the stored (original) one, and therefore, verifying the signature fails! Any help would be much appreciated as I can't proceed in my project without solving this problem. Here is the code to do the above mentioned functionality:
    //This part stores the signature (VT) in the table TTPTrans
    try
    { con = connect();
    ps = con.prepareStatement("UPDATE TTPTrans SET VT = ?, SigVT = ? WHERE TransID = ?");
    ps.setBinaryStream(1, new ByteArrayInputStream(vt), vt.length);
    ps.setBinaryStream(2, new ByteArrayInputStream(sigvt), sigvt.length);
    ps.setString(3, tID);
    ps.executeUpdate();
    ps.close();
    con.close();
    catch (Exception e)
    {  System.err.println(e.getMessage());
    e.printStackTrace();
    //This part retrive the signature from the table in the byte array o1:
    ResultSet result;
    byte[] o1 = null;
    byte[] o2 = null;
    try
    { con = connect();
    Statement statement = con.createStatement();
    result = statement.executeQuery("SELECT VT, SigVT" +
    " FROM TTPTrans" +
    " WHERE TransID = " + "'" +
    transID + "'");
    while (result.next()) {
    o1 = result.getBytes("VT");
    o2 = result.getBytes("SigVT");
    statement.close();
    con.close();
    catch(Exception e)
    { System.err.println(e.getMessage());
    e.printStackTrace();
    }

    In the following code, I use a ASN1SDSSSignature class, which is a subclass that I created from the Siganture class, to create and verify an SDSS signature. The ASN1SDSSSignature has two ASN1Integer class variables:
    signcryption = token.getSigncryption();
    sig.initVerify(ttpCert);
    sig.update(receivedVT);
    boolean verified = sig.verify(receivedSigVT);
    if(!verified)
    System.err.println("TTP signatire on received token invalid. ");
    notify()
    return;
    Where receivedVT and receivedSigVT are the byte arrays retrieved from th database. The following exception is thrown when I run the application:
    ASN1 type mismatch!
    Expected: codec.asn1.ASN1Integer
    In: ASN1SDSSSignature
    At index 0
    Got tag: 4 and Class: 0
    I hope this would clarify the situation and thanks in advance for any comments you may post.

  • Reading in any file and converting to a byte array

    Okay what I am trying to do is to write a program that will read in any file and convert it into a int array so that I can then manipulate the values of the int array and then re-write the file. Once I get the file into an int array I want to try and compress the data with my own algorithm as well as try to write my own encryption algorithm.
    What I have been looking for is code samples that essentially read in the file as a byte array and then I have been trying to convert that byte array into an int array which I could then manipulate. So does anyone have any sample code that essentially takes a file and converts it into an int array and then converts it back into a byte array and write the file. I have found code that is close but I guess I am just too new to this. Any help would be appreciated.

    You can read a whole file into a byte array like this:File f = new File("somefile");
    int size = (int) f.length();
    byte[] contents = new byte[size];
    DataInputStream in = new DataInputStream(
                              new BufferedInputStream(new FileInputStream(f)));
    in.readFully(contents);
    in.close();Note that you need to add in the proper exception handling code. You could also use RandomAccessFile instead of the DataInputStream.
    Writing a byte array to a file is easier; just construct the FileOutputStream, call write on it with the byte array, and close the stream.

Maybe you are looking for

  • How can I see/find my history?

    I was looking through my history with one of my contacts but it only goes so far as around  months back but when I checked my preferences it shows as Forever, and I have some contacts (with whom I don't speak often nor much) whose conversation histor

  • I get an error message..failed to load...missing msvcr80.dll

    Itunes showed me that an newer version of Itunes was available. after downloading  i get an error message "This application has failed to start because MSVR80.dll was not found..Re-installing the application may fix this problem.  I then uninstalled

  • HRMS Budgeting in 11.5.10.2 -- Guidance Please

    Hello, Does anyone have any guidance / overview / set-up documentation or information regarding the new 11.5.10 HRMS Budgeting functionality? Need to implement from new for a client. They have no existing budgets to convert. Thank you, Peter.

  • Xcelsius Support for Right to Left languages

    Hi, I'm having issues with Xcelsius and the way it handles right to left languages such as Farci. The text is rendered properly in excel but once bound to a control (like a label) the text is displayed reversed or words are reordered. I'm using Xcels

  • Finding tables used for all modules t code

    hi Gurus I just come accross to one answer that enter T.Code se49 & in that screen enter the T.Codes you want to see teh tables used for that t code. But when i enter t code se49 the system says it does not exists. Does it have any varsion problem ?