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.

Similar Messages

  • 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

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

  • 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

  • What is the best way to convert a cluster into byte array or string

    I'm writing a program that sends UDP packets and I've defined the data I want to send via large clusters (with u8/u16/u32 numbers, u8/u16/u32 arrays, and nested clusters). Right before sending the data, I need to convert the clusters either into strings or byte arrays. The flatten to string function is almost perfect for this purpose. However, it's appending lengths to arrays and strings which renders this method useless, as far as I can tell. 
    As I have many of these clusters, I would rather not hard code the unbundle by names and converting/typecasting to byte arrays or strings for each one. 
    Is there a feature or tool I am overlooking? 
    Thank you! 

    deceased wrote:
    Flatten to string has a boolean input of "Prepend string or array size" ... The default value is true.
    That only specifies if a string or array size should be prepended if the outermost data element is a string or array. For embedded strings or arrays it has no influence. This is needed for the Unflatten to be able to reconstruct the size of the embedded strings and arrays.
    The choice to represent the "Strings" (and Arrays) in the external protocol to LabVIEW strings (and arrays) is actually a pretty bad one unless there is some other element in the cluster that does define the length of the string. An external protocol always needs some means to determine how long the embedded string or array would be in order to decode the subsequent elements that follow correctly.
    Possible choices here are therefore:
    1) some explicit length in the protocol (usually prepended to the actual string or array)
    2) a terminating NULL character for strings, (not very friendly for reliable protocol parsing)
    3) A fixed size array or string
    For number 1) and 2) you would always need to do some special processing unless the protocol happens to use explicitedly 32 bit integer length indicators directly prepended before the variable sized that.
    For number 3) the best representation in LabVIEW is actually a cluster with as many elements inside as the fixed size.
     

  • How can i convert object to byte array very*100 fast?

    i need to transfer a object by datagram packet in embeded system.
    i make a code fallowing sequence.
    1) convert object to byte array ( i append object attribute to byte[] sequencailly )
    2) send the byte array by datagram packet ( by JNI )
    but, it's not satisfied my requirement.
    it must be finished in 1ms.
    but, converting is spending 2ms.
    network speed is not bottleneck. ( transfer time is 0.3ms and packet size is 4096 bytes )
    Using ObjectOutputStream is very slow, so i'm using this way.
    is there antoher way? or how can i improve?
    Edited by: JongpilKim on May 17, 2009 10:48 PM
    Edited by: JongpilKim on May 17, 2009 10:51 PM
    Edited by: JongpilKim on May 17, 2009 10:53 PM

    thanks a lot for your reply.
    now, i use udp socket for communication, but, i must use hardware pci communication later.
    so, i wrap the communication logic to use jni.
    for convert a object to byte array,
    i used ObjectInputStream before, but it was so slow.
    so, i change the implementation to use byte array directly, like ByteBuffer.
    ex)
    public class ByteArrayHelper {
    private byte[] buf = new byte[1024];
    int idx = 0;
    public void putInt(int val){
    buf[idx++] = (byte)(val & 0xff);
    buf[idx++] = (byte)((val>>8) & 0xff);
    buf[idx++] = (byte)((val>>16) & 0xff);
    buf[idx++] = (byte)((val>>24) & 0xff);
    public void putDouble(double val){ .... }
    public void putFloat(float val){ ... }
    public byte[] toByteArray(){ return this.buf; }
    public class PacketData {
    priavte int a;
    private int b;
    public byte[] getByteArray(){
    ByteArrayHelper helper = new ByteArrayHelper();
    helper.putInt(a);
    helper.putInt(b);
    return helper.toByteArray();
    but, it's not enough.
    is there another way to send a object data?
    in java language, i can't access memory directly.
    in c language, if i use struct, i can send struct data to copy memory by socket and it's very fast.
    Edited by: JongpilKim on May 18, 2009 5:26 PM

  • 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

  • Convert variable into an array

    I have variable, abc; whose value is in the format val1,val2,val3,..
    I want to convert it into an array, like that arr[0]=val1; arr[1]=val2; so on. How can I do this?
    Usman

    examine this class that I did
    import java.lang.*;
    public class ReadString {
    public static void main(String[] args){
    String abc = "1,2,3,4,5,6";
    StringBuffer abc2 = new StringBuffer(abc);
    int arrayLength = abc2.length(); //get length
    int[] abcFinal = new int[6];
    for (int i=0; i<arrayLength; i++) { //test characters
         int anIndex;
         if (!(abc2.substring(i,i+1)).equals(",")) { //if it is a number
         //(i/2) is ta little formula to be able to assign the
         //right index in the intArray to the number
         anIndex = (i/2);
         //set value to array
         abcFinal[anIndex] = Integer.parseInt(abc2.substring(i,i+1));
    for (int j=0;j<abcFinal.length;j++ ) {
         System.out.println("i = " + j + " value = " + abcFinal[j]);
    }//end main
    }//end class

  • Converting String to byte array

    Hi,
    There is a code for converting String to byte array, as follows:
         public byte[] toByteArray(String s)
              char[] c = s.toCharArray();
              int len = c.length;
              byte[] b = new byte[len * 2];
    for ( int i = 0 ; i < len ; i++ )
         b[i * 2] = (byte)(c);
         b[(i * 2) + 1] = (byte)(c[i] >> 8);
    return b;
    But this isn't doing the conversion properly. For example, for the � (euro) symbol, it converts to some other unreadable symbol. Also, same is the case for square brackets. Any idea why this' so? What's wrong with the above code?
    The encoding format is UTF-8.
    Thanks.

    > In fact, I tried with String.getBytes() too, but leads to the same problem, with those specific symbols.
    Did you try the String.getBytes(String charsetName) method?
    Both methods have been around since Java 1.1.
    It's an extremely important skill to learn to read the API and become familiar with the tools you will use to program Java. Java has an extensive set of online documentation that you can even download for your convenience. These "javadocs" are indexed and categorized so you can quickly look up any class or method. Take the time to consult this resource whenever you have a question - you'll find they typically contain very detailed descriptions and possibly some code examples.
    Java� API Specifications
    Java� 1.5 JDK Javadocs
    Best of luck!
    ~

  • Converting an image into numeric array?

    I want to sum all the pixel values in a image. I was thinking of using the Add Array Elements VI. Is their an easy way to convert an U8 or an I16 bit image into a numeric array? Thank you in advance.

    Is this a BW image? (If the image is paletted or color, a summing operation is poorly defined! )
    Just convert your image data to a 2D boolean array using unflatten pixmap, then feed the 1bit pixmap to "boolean to 0..1" followed by the SUM operation (in case it overflows, you might want to convert it to a better representation before summing, e.g. DBL. "boolean to 0,1" generates I16).
    Message Edited by altenbach on 06-01-2005 02:44 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    SumImage.png ‏2 KB

  • How can I convert a bitmap image into an array in LabVIEW 6.0.2, then to a spreadsheet for further analysis without NI-IMAQ or Vision?

    I do not have NI-IMAQ or NI Vision.
    I acquired the image using a picolo board then just saved it as a bitmap file.

    You want to convert it to an array of what? Of numbers? Of LabVIEW colors?
    The "Read BMP File.vi" VI outputs a 1-D array of the pixels, but I suspect it is not exactly in the format that you need. I am NOT sure, but I think that each group of 3 elements of that 1-D array (which is inside the cluster "image data" that the VI outputs) represents the red, green and blue levels of a single pixel (but it may be hue, saturation and lum.). Also, since it is a 1-D array, you would have to divide it by the width (which is also included in the "image data" cluster) to get some sort of 2-D array of data.
    You can find the "Read BMP File.vi" VI in the functions palete> "Graphics & sound">"Graphics Formats".

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

  • Grabbing Pixels from an image into an array

    Hi,
    I am new to the image processing using java. I want to get the pixel values of an image and store it into an text file. Can anyone help me with this?
    This is what i've done yet? Is the values present in the text field the correct values of the pixels of the image.
    import java.awt.*;
    import java.awt.image.*;
    import java.applet.*;
    import java.util.*;
    public class grabber extends Applet {
    private TextField tf;
    private TextArea ta;
    private Label status;
    private Canvas drawarea;
    private Image img=null;
    int ppmline=0;
    public void init() {
         setLayout(new GridLayout(1,2));
         Panel left=new Panel();
    left.setLayout(new BorderLayout());
    Panel topleft = new Panel();
    topleft.setLayout(new GridLayout(1, 4));
    topleft.add(tf=new TextField());
         Panel buttonsP = new Panel();
    buttonsP.add(new Button("Load GIF"));
         buttonsP.add(new Button("PPM Output"));
         topleft.add(buttonsP);
    left.add("North", topleft);
    left.add("Center", drawarea=new Canvas());
         left.add("South", status=new Label());
         add(left);               // left side of the applet.
         add(ta=new TextArea());          // right side.
         status.setText("See GIF files below.");
    public void paint(Graphics appletg) {
         Graphics g=drawarea.getGraphics();
         if (img != null) {
              g.drawImage(img, 0, 0, this);
              g.dispose();
    public boolean action(Event evt, Object arg) {
         String s=(String) arg;
         if(s.equals("Load GIF")) {
              img=getImage(getCodeBase(), tf.getText());
              repaint();
         else if (s.equals("PPM Output")) getPixs();
    return true;
    void getPixs() {
         int w=30, h=30;
         // PPM output starts.
         ta.setText("P3\n");
         ta.appendText(Integer.toString(w) + " " + Integer.toString(h) + "\n");
         ta.appendText("255\n");
         handlepixels(img, 0, 0, w, h);
    public void handlesinglepixel(int x, int y, int pixel) {
         // pixel is in RGB model. It is a 4-byte long integer.
         // It is converted into the string representation of PPM pixels.
         // ie. Hex 0x00102030 becomes "16 32 48"
         String s= Integer.toString((pixel & 0x00FF0000) >> 16) + " "
              + Integer.toString((pixel & 0x0000FF00) >> 8) + " "
              + Integer.toString(pixel & 0x000000FF) + " ";
    // If we use PPM RAW format, then we have to use ascii characters instead.
    //     char c[]= {(char) ((pixel & 0x00FF0000) >> 16),
    //          (char) ((pixel & 0x0000FF00) >> 8) ,
    //          (char) (pixel & 0x000000FF) };
    //     String s=new String(c);
         if (ppmline++>=3) {                // comment out if you use RAW format.
              ta.appendText(s + "\n");      // comment out if you use RAW format.
              ppmline=0;               // comment out if you use RAW format.
         } else                          // comment out if you use RAW format.
              ta.appendText(s);
    public void handlepixels(Image img, int x, int y, int w, int h) {
    int[] pixels = new int[w * h];
    PixelGrabber pg = new PixelGrabber(img, x, y, w, h, pixels, 0, w);
    try {
    pg.grabPixels();
    } catch (InterruptedException e) {
    System.err.println("interrupted waiting for pixels!");
    return;
    if ((pg.status() & ImageObserver.ABORT) != 0) {
    System.err.println("image fetch aborted or errored");
    return;
    for (int j = 0; j < h; j++) {
    for (int i = 0; i < w; i++) {
    handlesinglepixel(x+i, y+j, pixels[j * w + i]);

    im not at home or id post some source code but first off
    if your going to write a file from a applet your going to
    have to get by permisions.
    so you should probably do this with a application
    it would be alot easier
    use toolkit.getdefaulttoolkit() to get the image then
    use the pixel graber class to read it into a array
    of the type you want string or char
    then just write it into a file each element of the array
    and when you want to read it just read it in with file reader
    you could probaly do a test run just write in each value as
    a string and put a comma between each value then use
    stringtokenizer to read it back in its less efficient but
    for a test run it would make things clearer
    sorry if its not much help

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

  • Multiplatform: how convert int into byte[]???

    Hi all,
    I need to convert an int value into an array of bytes. An int is represented by 4 bytes, but the problem is that depending on the platform, the most significant byte is the first or the last, so if you convert it directly, like:
    int i = 5;
    byte b[] = new byte[4];
    b[0] = (byte)( (i & 0xff000000) >>> 24);
    b[1] = (byte)( (i & 0x00ff0000) >>> 16);
    b[2] = (byte)( (i & 0x0000ff00) >>> 8);
    b[3] = (byte)( (i & 0x000000ff) );
    you cannot export it to another platfroms.
    Thank you in advance.

    Come on, nobody knows how to detect the byte order in a given platform?
    I've been all the day dealing with this, which means all day without producing.
    Please, it�s very urgent.
    Thank you again.

Maybe you are looking for

  • Adobe Flash Builder 4.5 has stopped working

    My Adobe Flash Builder 4.5 has stopped working. I receive the following error when trying to start: An error has occured. See the log file C:\ Documents and Settings.......\.metadata.log I have attached the file. I have searched the web to try and fi

  • Update time capsule, since ipod not connect wifi to time capsule

    Hello, Since I update my Time Capsule(7.5.1), I cannont connect my ipod touch to wifi time Capsule. message ipod is : impossible de rejoindre le réseau RES_Didier My iMac is connected, my PC Windows is connected ans my Apple TV to. Only my ipod canno

  • Transport Organizer Syntax Check using the Code Inspector

    dear fellows, i'm facing a problem when i check the syntax of transport. When i'm using the option to check the syntax within the transaction se01 the system starts no longer the extended check but the code inspector. is there any possibility to turn

  • Hyper-V bridge (Wi-Fi external network) stopped working

    Well, that: Used to work, had to remove it. I added it back a couple of hours later and now it isn't working. I can bridge the connections and Wi-Fi seems to connect. But the other connection won't work on the parent OR child machine. I also tried a

  • How to insure that contacts and calendar are NOT synced with ICloud?

    Hello, I do not understand, why it is not possible anymore to sync your contacts and calendar data between your mac book and your mobile devices using USB cable. I also heard that with Maverick and Itunes 11.1.2 you can not sync anything using USB an