Image to byte array

hello,
how can i get an image in jar file as a byte[] or can i convert an image to byte[]?
thx...

To read a bytes from a jar file, use a JarInputStream. If you're just trying to read bytes from a jar, it doesn't make any difference whether it's an image or not.
To get the bytes from an Image, you need to put more information in your question - are you talking about an image file, like a JPEG or TIFF? What do you want to do with it? Or are you talking about an Image object in Java? If so, which specific concrete subclass, and what do you want to do with it?

Similar Messages

  • Display image from byte array

    Hello Everybody,
    I need to display an image given in a byte array, how can I show this image in a JFrame?
    1. I tryied saving the image in a .jpg file,
         File file1 = new File("Path to my destination image");2. then I use a FileOutputStream to save the image in the path:
            FileOutputStream fos1 = new FileOutputStream(docu);
            fos1.write(ImageInbyteArray);
            fos1.close();3. Once I have the image in a file I'm trying to load it using a JButton, but the JButton doesn't display the image. I think that for some unknown (at least for me ;-) reason the file isn't still available to be used in the ImageIcon, this is my code:
            imgIconDocu = new ImageIcon("Path to my destination image");
            jBtnDocu = new JButton(imgIconDocu);What's wrong here?
    Thanks a lot

    Does the byte array contain a JPEG image? Where did
    you get the contents of the byte array?yes the array contains the JPEG image, I have a database in PostgreSQL, and the images are stored in blob in the database. I have to call a service in the server and in return it gives me the 3 images as byte arrays, that's the reason I only have the byte arrays. so I tryed saving the images as jpeg files in my hard disk to show them, but it appears that they are not available to show them in Swing after saving them. I can only show the images if I close my application and start it again :-(
    I tryed flushing and closing the FileOutputStream after the writting process (fos.write(bytearrayImage);
    fos.flush();
    fos.close();)
    Y also tryed:
    fos.write(bytearrayImage);
    fos.close();
    fos.flush();But it doesn't work either :-(
    What do you recommend me?.
    Thanks a lot,
    Johnny G L

  • Converting image into byte array

    Hi all,
    How to convert an integer array image into byte array ?
    here i have a image like this :
    private static int pixelArray[] = {
    0xff000000, 0xff000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
    0xff000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000
    From this one i create image like this one :
    Image image = Image.createRGBImage(pixelArray, width, height, true);
    Now i want to convert that pixelArray into byte array ? how to do this
    additionally i want to send this byte array to servlet .
    thanks in advance.

    Hi,
    If you want to convert your int array to a byte array you should
    split each integer into 4 bytes to avoid losing information. You can
    rebuild your integer array later if you need to. I think this code
    will work (i havent tested it):
    byte[] pixel= new byte[pixelArray.length<< 2];
    for (int i= pixelArray.length- 1; i>= 0; i--) {
      int aux= i<< 2;  // i* 4 = i<< 2
      pixel[aux]=    (byte) (pixelArray>> 32);
    pixel[aux+ 1]= (byte) (pixelArray[i]>>> 16);
    pixel[aux+ 2]= (byte) (pixelArray[i]>>> 8);
    pixel[aux+ 3]= (byte) pixelArray[i];
    Greets.

  • Create image from byte[]array on server side

    Hello everyone..
    I'm developing an application which will take snapshots from a mobile device, and send it to my pc via bluetooth. I have my own midlet which uses the phone camera to take the snapshot, i want to transfer that snapshot to my pc.
    The snapshot is taken is stored in an array byte.
    The image can be created on the phone itself with no problem using : image.createImage(byte[])
    my problem is that when i send the array byte via bluetooth, and receive it on the server, i cannot create the image using the :image.createImage() code
    The connection is good since i have tested by writing the content of the array in a text file.
    Piece of midlet code:
                try{
                     stream = (StreamConnection)Connector.open(url);
                     OutputStream ggt = stream.openOutputStream();
                     ggt.write(str);
                     ggt.close();
                }catch(Exception e){
                     err1  = e.getMessage();
                }where str is my array byte containing the snapshot
    And on my server side:
    Thread th = new Thread(){
                   public void run(){
                        try{
                             while(true){
                                  byte[] b = new byte[in.read()];
                                  int x=0;
                                  System.out.println("reading");
                                  r = in.read(b,0,b.length);
                                  if (r!=0){
                                       System.out.println(r);     
                                       img = Image.createImage(b, 0, r);
                                                            //other codes
                                       i get this error message:
    Exception in thread "Thread-0" java.lang.UnsatisfiedLinkError: javax.microedition.lcdui.ImmutableImage.decodeImage([BII)V
         at javax.microedition.lcdui.ImmutableImage.decodeImage(Native Method)
         at javax.microedition.lcdui.ImmutableImage.<init>(Image.java:906)
         at javax.microedition.lcdui.Image.createImage(Image.java:367)
         at picserv2$1.run(picserv2.java:70)
    Please anyone can help me here? is this the way to create the image on the server side? thx a lot

    here is exactly how i did it :
    while(true){
                                  byte[] b = new byte[in.read()];
                                  System.out.println("reading");
                                  r = in.read(b, 0, b.length);
                                  if (r!=0){
                                       Toolkit toolkit = Toolkit.getDefaultToolkit();
                                       Image img = toolkit.createImage(b, 0, b.length);
                                       JLabel label = new JLabel(new ImageIcon(img) );
                                       BufferedImage bImage = new BufferedImage(img.getWidth(label),img.getHeight(label),BufferedImage.TYPE_INT_RGB);
                                       bImage.createGraphics().drawImage(img, 0,0,null);
                                       File xd = new File("D:/file.jpg");
                                       ImageIO.write(bImage, "jpg", xd);
                                       System.out.println("image sent");
                             }Edited by: jin_a on Mar 22, 2008 9:58 AM

  • Reducing size of Image or byte array

    Hello,
    I am making a program where i have to send user's screen to another PC,
    So I use class Robot to make a screen capture and send it via UDP.
    However this is still too slow, my question is: is there some library to compress the size of byte array or Image?
    Thanks for help,
    Juraj

    thanks for help i found it
    byte[] input = ...;
    // Create the compressor with highest level of compression
    Deflater compressor = new Deflater();
    compressor.setLevel(Deflater.BEST_COMPRESSION);
    // Give the compressor the data to compress
    compressor.setInput(input);
    compressor.finish();

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

  • Converting Image to Byte Array and then to String

    Hi All...
    Can anyone please help me. I have got a problem while converting a Byte array of BufferedImage to String.
    This is my code, First i convert a BufferedImage to a byte array using ImageIO.wirte
    public String dirName="C:\\image";
    ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
    BufferedImage img=ImageIO.read(new File(dirName,"red.jpg"));
    ImageIO.write(img, "jpg", baos);
    baos.flush();
    byte[] resultimage=baos.toByteArray();
    baos.close();
    Then i tried to convert this byte array to a string
    String str=new String(resultimage);
    byte[] b=str.getBytes();
    This much worked fine. But when i reversed this process to re-create the image from that string. i found the image distroted.
    BufferedImage imag=ImageIO.read(new ByteArrayInputStream(b));
    ImageIO.write(imag, "jpg", new File(dirName,"snap.jpg"));
    I got this snap.jpg as distroted.
    Please help me i have to convert the image to a string and again i have to re-create the image from that string.

    To conver the bytearray to string use base64.encoding
    String base64String= Base64.encode(baos.toByteArray());
    To convert back use Base64.decode;
    byte[] bytearray = Base64.decode(base64String);
    BufferedImage imag=ImageIO.read(bytearray);

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

  • How to change the image into byte and byte array into image

    now i am developing one project. i want change the image into byte array and then byte array into image.

    FileInputStream is = new FileInputStream(file);
    byte[] result = IOUtils.toByteArray(is);
    with apache common IO lib

  • Reading an image in byte form

    hii guys
    i m trying to read an image and convert it to byte array and later to do some change in that byte array and later recreate a new image.
    For that i m using FileInputStream and FileOutputStream and its read and write methods
    but now i dont know how to append that byte and recreate that image.
    actually i want to do that , convert the image in byte array form and replacing some bytes of the image by my text msg bytes and recreate a new image.
    how an i do that.
    plz help me.
    its urgent.

    import java.io.*;
    class image
    public static void main(String[] arg) throws IOException
    String msg;
    int len,i;
    FileInputStream fin;
    FileOutputStream fout;
    try
    try
    fin=new FileInputStream("01.jpg");
    catch( Exception e)
    System.out.println("Input image not found");
    return;
    try
    fout=new FileOutputStream("001.jpg");
    catch( Exception e)
    System.out.println("output image cannt be created");
    return;
    catch(Exception e)
    System.out.println("output image cannt be created");
    return;
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the secret msg :: ");
    msg=br.readLine();
    byte[] msg1=msg.getBytes();
    len=msg1.length;
    System.out.println(len);
    for(i=0;i<len;i++)
    System.out.println(msg1);
    try
    do
    byte by=(byte)fin.read();
    //System.out.print(" "+by);
    if(fin.available()>0)
    fout.write(by);
    }while(fin.available()>0);
    catch(Exception e)
    System.out.println("File error");
    fin.close();
    fout.close();
    till now i only imputed the sg , change it into byte form .
    now i want to replace the msg bytes into the image byte as :- 1 image byte ,1 msg byte, 1 image byte , 1 msg byte........ so on
    until the msg bytes are not finished.

  • Images, Thumbnails, byte[ ] and BLOB

    Hi guys,
    This is what I have to do:
    User selects image from disk and i'm putting it into DB (IBM DB2 8.0). That's clear. No problem.
    But I need that image as a thumbnail as well (I have to show images as thumbnails for each Item). I have a DB table IMAGE with 2 columns - IMAGE_FULL and IMAGE_THUMBNAIL.
    So I need to scale image(wich I have as byte array, or struts FormFile) and than put it into DB as Thumbnail.
    Or even if I don't have IMAGE_THUMBNAIL column, I have to get image as byte array from IMAGE_FULL column, scale it and show it in the browser.
    So, if I explained correctly and not very complicated way, can anyone give some ideas?
    Thanks in advance
    Gio

    For thumbnails, there's plenty of examples of resizing and saving images in the Java Programming forum, just do a search.
    For the database storage and retrieval... I had found some really good site with database examples, but I can't find it anymore.... but here's some code:
    // store
                   PreparedStatement pstmt = db.getConnection().prepareStatement(
                        "INSERT INTO TeeColor VALUES( ?, ? )" );
                   pstmt.setString(1, "yellow");
                   File fImage = new File("yellow.gif");
                   InputStream isImage = new FileInputStream(fImage);
                   pstmt.setBinaryStream(2, isImage, (int)fImage.length());
                   int res = pstmt.executeUpdate();
    // load
                   Statement stmt = db.getConnection().createStatement();
                   ResultSet rs = stmt.executeQuery(
                        "SELECT TCBlob FROM TeeColor WHERE TColor = 'Yellow'");
                   if(rs.next()) {
                        byte[] bytes = rs.getBytes("TCBlob");
                        JFrame f = new JFrame("test");
                        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                        f.getContentPane().add(new JLabel(new ImageIcon(bytes)));
                        f.pack();
                        f.show();
                   }

  • 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();
      }

  • 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" />

  • Setting attributes of image stored in byte array in servlet

    Hi,
    I am using a servlet to stream image (GIF) to the browser.
    Image is accessed by browser using the img tag. src attribute points to the servlet which send the image stream.
    Servlet has the image as the array of bytes. It simply write these bytes on the response object's output stream. It does not use any encoder.
    I get the image on the browser. But when I try to see the properties of the image I don't see the type of image. I also don't see the created time, modified time and size of the image. When I do Save As on this image it tries to save it as BMP instead of GIF. Also when I do the print preview I don't see the image in the preview window. When I try to print the web page, it prints everything except this image. I get small cross(image missing) on the printed page.
    I would like to know why the image attributes on browser go missing and why can't I print the image?
    I would like to add that I am getting the image as the array of bytes from a different application on which I do not have control.
    Thanks.

    Hi,
    I am using a servlet to stream image (GIF) to the browser.
    Image is accessed by browser using the img tag. src attribute points to the servlet which send the image stream.
    Servlet has the image as the array of bytes. It simply write these bytes on the response object's output stream. It does not use any encoder.
    I get the image on the browser. But when I try to see the properties of the image I don't see the type of image. I also don't see the created time, modified time and size of the image. When I do Save As on this image it tries to save it as BMP instead of GIF. Also when I do the print preview I don't see the image in the preview window. When I try to print the web page, it prints everything except this image. I get small cross(image missing) on the printed page.
    I would like to know why the image attributes on browser go missing and why can't I print the image?
    I would like to add that I am getting the image as the array of bytes from a different application on which I do not have control.
    Thanks.

Maybe you are looking for

  • Why can't I 'place' a signature into a .pdf form created in LiveCycle Designer 9???

    Hi there, I have been pulling my hair out all afternoon! I have created a dynamic form in LiveCycle Designer 9 - saved it as a Dynamic XML Form - opened it in Acrobat X - saved it as Reader Extended PDF and Enabled Additional Features. My colleagues

  • Editing text in Dreamweaver CS4 on Mac 10.6.2 causes paragraph ends to disapear

    Editing text in Dreamweaver CS4 on Mac 10.6.2 causes paragraph ends to disappear. When adding bold in design view (strong) to two words at the start of my paragraph the last line of the paragraph disappears. This is somewhat worrying as it means any

  • Please answer me..

    is it possible to play the received media stream without installing jmf(that is, only by using jmf jars..)?.. i tried it.. but it play the audio.. but it didnt play video.. but with jmf installed .. it play audio as well as video

  • ORA-06550 and PLS-00201 in PL/SQL Developer

    Hi all , I am facing the following error when i try to view the DDL of a table using pl/sql developer. ( right click on table and then DBMS_Metadata -> DDL) ORA-06550: line 7, column 5: PLS-00201: identifier 'SYS.DBMS_LOB' must be declared ORA-06550:

  • Help - SAP Legal requirements South / Central America

    Hello , I am in the initial stage of implementing SAP for Andina countries. The list is as below 1. Chile ,Peru ,Colombia , Venezuela 2.  Panama ,Guatemala ,Costa Rica  , 3.  Ecuador ,Trinidad & Tobago ,Domican Republic Countries in point 1, I manage