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?

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.
Thanks much for the code -

Similar Messages

  • How Convert a Byte array to a image format

    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|] 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 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()
            short length;
            while (true)
                DataInputStream din = null;
                    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);
                catch (Exception ex)
    }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

    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

    I have pasted code for servlet's doGet method which writes image data...
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    ServletException, IOException
    HttpSession session = request.getSession(); //taking httpsession
    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 = 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" ..

  • 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????

    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????

  • 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
    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("");
    FileOutputStream fos = new FileOutputStream(getServletContext().getRealPath(""));
    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 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:
    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)
    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[]

  • 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 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 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 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.

    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
    ServletOutputStream os = response.getOutputStream();
    // i get byte array from loDocumentDVO.getFileContents():
    byte[] fileContent = loDocumentDVO.getFileContents();

    Thank you for your sharp words.
    I have now compiled the ImageServlet I have adapted slightly from
    I am trying to run it with
    <img src="image?file=plan.jpg" alt="Plan" />
    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
    The servlet code is
    package example;
    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 {
            // Prepare file object.
            File imageFile = new File(imageFilePath, imageFileName);
            // Check if file actually exists in filesystem.
            if (!imageFile.exists()) {
            // 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:
            if (contentType == null || !contentType.startsWith("image")) {
            // 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.
                    "Content-disposition", "inline; filename=\"" + imageFileName + "\"");
                output = new BufferedOutputStream(response.getOutputStream());
                // Write file contents to response.
                while (contentLength-- > 0) {
                // Finalize task.
            } catch (IOException e) {
                // Something went wrong?
            } finally {
                // Gently close streams.
                if (input != null) {
                    try {
                    } catch (IOException e) {
                        // This is a serious error. Do more than just printing a trace.
                if (output != null) {
                    try {
                    } catch (IOException e) {
                        // 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?

  • 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.....

    To convert an Image to bytes you can use the Image.getRGB() method.[], int, int, int, int, int, int)

  • 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.

    I got it figured out. It does make the TIFF a little bit larger but that's ok.
    RenderedOp src = JAI.create("stream", new;
    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?

    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}
    {color:#000080}Cross posting is rude.

  • 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);
            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";
        } 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();
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(imageByteArray, 0, imageByteArray.length);
        // alternative to connect is to get & close the input stream
        // connection.getInputStream().close();

Maybe you are looking for

  • Disabled attribute on link causes Return Listener disfunctioning

    Hello, Using JDev 11g Studio Edition Version I have a af:commandImageLink which, when clicked on, opens a Dialog. On the af:commandImageLink, a returnListener is defined and there is an EL expression on the disabled attribute. When the EL

  • Query with "not in" no longer working

    I created a query to show customers that had not been contacted (i.e.- did not have an activity) in B-one in the last 30 days so the salespeople could do follow up. they started using activities in January and now here in May-something is amiss. Now

  • Labview installation - not compatible directory

    I have problem with installing LabVIEW 2014 64bit on my Windows 8.1 Proffesional 64 bit machine. Story: I downloaded LabVIEW 2014 and installed it only to find out its 32bit version. I wandted 64bit version so when i found it i downloaded it. Then i

  • Where's the fix for CIT200's disconnected message?

    My phone recently started showing the disconnected message. The phone simply isn't connecting to Skype but linksys shows connected in the taskbar (running xp). I've been searching for a solution to this problem in various forums and tried everything

  • Define and assign user authorization groups in FI

    Hi All, In order to allow some specific group of users to post in AUGR allowed periods, how do I define and assign user authorization groups in FI? Thanks, Teo