Byte array to png image conversion

hi friends
i am using a servlet using tomcat server to send multiple images to a client. i have stored all the images in a single byte array.and then encoded using base64. i am sending it to the client side and decoding it. when i extract the byte array and then try to convert it to image it shows an illegal argument exception.please help me?
Pradeep

dubwai
Just looked at your code again. Did you mean int,not
long?He wanted an unsigned int (which of course doesn't
exist in Java) and if you look at his original code it
was returning long.Well, it's not so much that I wanted an unsigned int, it's just that the data was stored as a 32 bit unsigned integer. Since the data represented numbers with a range of 0 to 2^32 - 1, the range exceeded what I could put in a Java int, thus I need to stuff it in a long - well, that was my reasoning anyway.
Thanks for the nio tip, I'd not looked into that stuff and really should.
Lee
Thanks much for the code -

Similar Messages

  • How Convert a Byte array to a image format

    Hi,
    How to convert a Byte array to an image format....I shall be more clear what i want...See i recieve a Byte array fom server this Byte array before recieveing at my end it was converted from an image/text format into a Byte array and is sent from server and, I recieve this Byte array now I have to convert this Byte array into their respective image....please tell me how to convert a Byte array to a image ......... Kindly explain clearly as i am new to Java......
    Thanking You.

    Note: This thread was originally posted in the [New To Java|http://forums.sun.com/forum.jspa?forumID=54] forum, but moved to this forum for closer topic alignment.

  • Byte array convert to image works fine for a peiod of time, Then error

    Hi all
    I'm on a program of reading incoming image set which comes as byte arrays through socket and convert them back to images using the method.
    javax.microedition.lcdui.Image.createImage();This works perfect for some time.
    But after 1 minute of running it gives an error
    java.lang.OutOfMemoryError: Java heap space
            at java.awt.image.BufferedImage.getRGB(Unknown Source)
            at com.sun.kvem.midp.GraphicsBridge.loadImage(Unknown Source)
            at com.sun.kvem.midp.GraphicsBridge.createImageFromData(Unknown Source)
            at sun.reflect.GeneratedMethodAccessor14.invoke(Unknown Source)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
            at java.lang.reflect.Method.invoke(Unknown Source)
            at com.sun.kvem.sublime.MethodExecution.process(Unknown Source)
            at com.sun.kvem.sublime.SublimeExecutor.processRequest(Unknown Source)
            at com.sun.kvem.sublime.SublimeExecutor.run(Unknown Source)My J2ME client code
    public class ChangeImage extends Thread
        private SocketConnection sock = null;
        private Image img = null;
        private CanvasKey canvas = null;
        private InputStream in = null;
        public ChangeImage(SocketConnection sock, Canvas canvas) throws IOException
            this.sock = sock;
            this.canvas = (CanvasKey) canvas;
            in = sock.openInputStream();
        public void run()
            super.run();
            short length;
            while (true)
                DataInputStream din = null;
                try
                    din = new DataInputStream(in);
                    length = din.readShort();     // to determine next data packet size
                    byte[] arr = new byte[length];  // next data packet store here
                    din.readFully(arr);  //read image
                    img = Image.createImage(arr, 0, arr.length);
                    canvas.setImage(img);
                    ChangeImage.sleep(50);
                catch (Exception ex)
                    ex.printStackTrace();
    }When I comment following line no error prints.
    img = Image.createImage(arr, 0, arr.length);So the problem is not with socket program.
    What is this problem? Think old image isn't being flushed!!! in the method javax.microedition.lcdui.Image.createImage();Please help me.

    Forgot to Mention i'm using Windows 8.1 - 32 GB Ram - i7-3970x - 2 SSd's in raid 0 for C Drive/ Storage drive is three ( 2 tb HDD in a raid 0 ) / Pictures Folder defaults to the Storage Drive not the Application drive .

  • Displaying the .png image stored in an byte array

    Hi,
    I have to download an .png image from a server and i have to store it in a byte array and i have to display this byte array in another servlet. I have written the code to get the image from the remote server in a java class. The java class returns the byte array of the image and i have to display that in an servlet.
    If anybody has the code or any refrence to refer please help me..
    Thanks & Regards
    -Sandeep

    I have pasted code for servlet's doGet method which writes image data...
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws
    ServletException, IOException
    HttpSession session = request.getSession(); //taking httpsession
    response.setContentType("image/jpeg");
    ServletOutputStream out = response.getOutputStream(); //taking outputstream of response
    if (rtn.getErrorCode() == 0)
    //this will actually write image file data from where it is being called
    //byte array will contain image data, please load your image into below byte array variable
    byte[] b = new byte[100];
    out.write(b);
    out = null; //making null
    session = null; //making null
    In other servlet, write <img> tag and specify its src attribute to the "name of servlet where u have pasted above code" ..
    Regards,
    Nikhil

  • Converting a PNG image to an array of bytes and vice versa..

    hi all,
    i need to convert a PNG image to an array of bytes ,then converting back this array of bytes to The PNG image again ,i read this can be done using output streams but i feel like a dump and i can't fix the whole thingy out ! ,can anybody help me in this ,by explaining how can this be established????
    Regards,
    D.Roth

    hi all,
    i need to convert a PNG image to an array of bytes ,then converting back this array of bytes to The PNG image again ,i read this can be done using output streams but i feel like a dump and i can't fix the whole thingy out ! ,can anybody help me in this ,by explaining how can this be established????
    Regards,
    D.Roth

  • Save byte array (image) to file with servlet

    Good day.
    I should must to save a png image to file.
    I have a byte array of the image.
    This work is in a servlet.
    How can I do it?
    Best regards.
    Stefano Errani

    Good day.
    I have a byte[] and then I have used
    FileOutputStream fos = new FileOutputStream(getServletContext().getRealPath("/public_html/mcfoto/foto1.png"));
    fos.write(bt, 0, bt.length); // byte[] bt
    fos.close();
    This on my web server that has public_html as root web directory.
    The server is in multi domain.
    In this mode I have an error.
    Then I have tryied to use
    FileOutputStream fos = new FileOutputStream("http://www.stefanoerrani.it/mcfoto/foto1.png");
    and
    FileOutputStream fos = new FileOutputStream(getServletContext().getRealPath("http://www.stefanoerrani.it/mcfoto/foto1.png"));
    In both ways I have obtained an error.
    At last I have tryied in my localhost (local machine) using
    FileOutputStream fos = new FileOutputStream(getServletContext().getRealPath("/mcfoto/foto1.png"));
    All run correclty.
    The Application Server is Tomcat with Apache HTTP Server.
    The first server (of www.stefanoerrani.it) has Linux as OS.
    My local server has Windows as OS.
    I should want, if it's possible, an help.
    Best regards.
    Stefano Errani

  • How to add byte[] array based Image to the SQL Server without using parameter

    how to add byte[] array based Image to the SQL Server without using parameter.I have a column in table with the type image in sql and i want to add image array to the sql image column like below:
    I want to add image (RESIM) to the procedur like shown above but sql accepts byte[] RESIMI like System.Drowing. I whant that  sql accepts byte [] array like sql  image type
    not using cmd.ParametersAdd() method
    here is Isle() method content

    SQL Server binary constants use a hexadecimal format:
    https://msdn.microsoft.com/en-us/library/ms179899.aspx
    You'll have to build that string from a byte array yourself:
    byte[] bytes = ...
    StringBuilder builder = new StringBuilder("0x", 2 + bytes.Length * 2);
    foreach (var b in bytes)
    builder.Append(b.ToString("X2"));
    string binhex = builder.ToString();
    That said, what you're trying to do - not using parameters - is the wrong thing to do. Not only it is insecure due to the risk of SQL injection but in the case of binary data is also inefficient since these hex strings are larger than the original byte[]
    data.

  • How to send byte array of image with 300dpi.

    Hello fiends
                       i am making an application in which i have to send the byte array of an image with 300dpi.
    so i am using image snapshot class for that and use that code.
                        var snapshot:ImageSnapshot = ImageSnapshot.captureImage(cnvParent,300);
                        var bdata:String = ImageSnapshot.encodeImageAsBase64(snapshot);
    but when i send that bdata to php end using httpService.The size at other end of image increases surprisingly.i means it will increase its actual height and actual width.so is there any way to overcome this increase in size when i bitmapped image at 300 dpi?
    if there any way then please tell me.waiting for your reply.
    Thanks and Regards
        Vineet Osho

    Thanks david for such a quick reply.the link is really helpful.So we have to calculate the screendpi thruogh our code and then set the height and width of image.is there any simple way to sort out my problem.i just want to print my image at 300dpi but i am using image snapshot class so its taking the snap of my container(image) and save the image at 96 dpi which is dpi of my screen(monitor).so is there any way or any class in flex through which i got the image at its original dpi.i am not stick on 300 dpi but i m getting image from backend through xml at 300dpi.thats why i want the byte array i am sending should be at 300dpi.i am totally confused now.so please help me.
    Thanks and regards
      Vineet osho

  • Image Byte Array

    How do we get byte array of an image(immutable/mutable) object.I want to save it in RMS tht is why i need to get the image in byte array form.
    I want to send mutable and immutable images through HTTP.Is it possible to do so ??Please Help.
    Thnks in advance.

    Why don't you just try in stead of asking questions. I'm not here to hold you hand on every step. The api docs should provide you with more than enough information to help you on your way. You'll just need to reed that information very well.

  • What is the best way to get an image as byte array

    Hi, I have an iamge stored in a file (jpg or gif) and I want to get the pixels as byte array. The image will be black and white only (tresholded) so byte will be enough to hold all the colors. What I'm doing now works but it just doesn't look good so I think there must be a better way.
    Thanks!

    just in case somebody else tries to do the same. When
    you first get the jpg image with the JPEG decoder and
    store it in a BufferedImage you can't get the pixel
    samples as byte arrays. You'll have to get them first
    as int[] and then make your own byte[].Anything coming in as pixels tends to be highly organized. You have this image array right. Now, how is it organized you must ask yourself? Then you can access it, bytewise or bitwise!

  • 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

  • Conversion of image into byte array

    I have a problem in converting .png image into bytestream, if anyone can help in this pls do so.....

    Hi,
    To convert an Image to bytes you can use the Image.getRGB() method.
    http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Image.html#getRGB(int[], int, int, int, int, int, int)
    -Henrik

  • Image Conversion with Byte Arrays

    I'm trying to read in a byte[] for JPG, PNG, BMP, and GIF files which will then be converted to a .TIFF file so it can be printed on Post Script printers.
    Technically I have it working BUT the catch is that it physically needs to create the file. I'd like to have it all done in memmory and not have to actaully have a physical file created.
    I have been trying many different things with the JAI.create function. Near as I can see so far that only creates a RenderedImage which then creats a file even if I use "stream" inscreat off "filename".
    Any suggestions would be appreciated.
    Thanks.

    I got it figured out. It does make the TIFF a little bit larger but that's ok.
    RenderedOp src = JAI.create("stream", new com.sun.media.jai.codec.ByteArraySeekableStream(image));
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    JAI.create("encode", src, out, "TIFF", null);
    return out.toByteArray();

  • How to create PNG file from byte array of RGB value?

    Hi
    Here is my problem.
    I have drawn some sketchs (through code in runtime) on canvas. I have grabbed the RGB information for the drwan image and converted to byte array.
    I have to pass this byte array to server and generate a png file and save.
    Please help.

    {color:#ff0000}Cross posted{color}
    http://forum.java.sun.com/thread.jspa?threadID=5218093
    {color:#000080}Cross posting is rude.
    db{color}

  • How to get a string or byte array representation of an Image/BufferedImage?

    I have a java.awt.Image object that I want to transfer to a server application (.NET) through a http post request.
    To do that I would like to encode the Image to jpeg format and convert it to a string or byte array to be able to send it in a way that the receiver application (.NET) could handle. So, I've tried to do like this.
    private void send(Image image) {
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        try {
            BufferedImage buffImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            ImageIcon imageIcon = new ImageIcon(image);
            ImageObserver observer = imageIcon.getImageObserver();
            buffImage.getGraphics().setColor(new Color(255, 255, 255));
            buffImage.getGraphics().fillRect(0, 0, width, height);
            buffImage.getGraphics().drawImage(imageIcon.getImage(), 0, 0, observer);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(stream);
            jpeg.encode(buffImage);
            URL url = new URL(/* my url... */);
            URLConnection connection = url.openConnection();
            String boundary = "--------" + Long.toHexString(System.currentTimeMillis());
            connection.setRequestProperty("method", "POST");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            String output = "--" + boundary + "\r\n"
                          + "Content-Disposition: form-data; name=\"myImage\"; filename=\"myFilename.jpg\"\r\n"
                          + "Content-Type: image/jpeg\r\n"
                          + "Content-Transfer-Encoding: base64\r\n\r\n"
                          + new String(stream.toByteArray())
                          + "\r\n--" + boundary + "--\r\n";
            connection.setDoOutput(true);
            connection.getOutputStream().write(output.getBytes());
            connection.connect();
        } catch {
    }This code works, but the image I get when I save it from the receiver application is distorted. The width and height is correct, but the content and colors are really weird. I tried to set different image types (first line inside the try-block), and this gave me different distorsions, but no image type gave me the correct image.
    Maybe I should say that I can display the original Image object on screen correctly.
    I also realized that the Image object is an instance of BufferedImage, so I thought I could skip the first six lines inside the try-block, but that doesn't help. This way I don't have to set the image type in the constructor, but the result still is color distorted.
    Any ideas on how to get from an Image/BufferedImage to a string or byte array representation of the image in jpeg format?

    Here you go:
      private static void send(BufferedImage image) throws Exception
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpeg", byteArrayOutputStream);
        byte[] imageByteArray = byteArrayOutputStream.toByteArray();
        URL url = new URL("http://<host>:<port>");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(imageByteArray, 0, imageByteArray.length);
        outputStream.close();
        connection.connect();
        // alternative to connect is to get & close the input stream
        // connection.getInputStream().close();
      }

Maybe you are looking for

  • Striped + Mirrored software RAID no longer mounting

    I have a MacPro 4,1 using the 4 internal bays each with a 1.5GB drive. Drives 1&2 are mirrored, drives 3&4 are mirrored. Those 2 mirrored drives are then striped together for a volume called 'Titanic.' Been working great for years, but just recently

  • Pdf will not open when created

    A recent problem has popped up.  When creating a new pdf document the save as window stays in the task bar until I click on it.  Once the pdf is created it stays in task bar until I click on it to view on it.  Using windows 7 and Adobe Pro 9 Extened.

  • Best phone for syncing with Office for Mac 2008?

    I'll be getting a new phone in a few months and I want to get one that syncs perfectly and effortlessly with Office for Mac 2008. I currently use a Motorola Q and a Macbook Pro and have to go through isyncing Office with the Mac versions (iCal and Ad

  • How to display amount in words in the last page

    Hi, I am very new to Oracle Report, but v.good experience in Crystal report. How can i display amount in words for an invoice amount total in the last page of the invoice and after total amount. I created a new non repeating frame and put the amount

  • Does the Canon HF G10 HDMI only output  29.97?

    Is the Canon HF G10 HDMI output limited to 29.97? I'm using the HDMI output of the Canon HF G10 to record to an external hard drive (I'm using a Blackmagic HyperDeck with an SSD). I set the camera to 24p (effectively 23.98) but the output - through t