How to convert a Image object to byte Array?

Who can tell me, how to convert Image object to byte Array?
Example:
public byte[] convertImage(Image img) {
byte[] b = new byte...........
return b;

Hello,
any way would suit me, I just need a way to convert Image or BufferedImage to a byte[], so that I can save them. Actually I need to save both jpg and gif files without using any 3rd party classes. Please help me out.
thanx and best wishes

Similar Messages

  • How to convert an Image to a byte array?

    I want to make a screenshot and then convert the image to a byte of arrays so I can send it through a BufferedOutputStream.
    try
                   robot = new Robot();
                   screenshot = robot.createScreenCapture(new Rectangle(500,500));
                   imageFile = new File("image.png");
                   ImageInputStream iis = ImageIO.createImageInputStream(screenshot);
                   byte[] data = new byte[1024];
                   byte[] tmp = new byte[0];
                   byte[] myArrayImage = new byte[0];
                   int len = 0;
                   int total = 0;
                   while((len = iis.read(data)) != -1 ) // LINE 52 --- EXCEPTION CATCHED HERE
                        total += len;
                        tmp = myArrayImage;
                        myArrayImage = new byte[total];
                        System.arraycopy(tmp,0,myArrayImage,0,tmp.length);
                        System.arraycopy(data,0,myArrayImage,tmp.length,len);
                   ios.close();I get this exception while running:
    Exception in thread "Thread-0" java.lang.NullPointerException
    at Server.run(Server.java:52)
    at java.lang.Thread.run(Unknown Source)

    Fixed that. I got a new problem.
    When I connect to my simple server application that reads the image file, converts it to an array of bytes and sends it back, the file is created on the client side and it containts data, but I am not able to open the image. I have checked that the image that the server is sending is working. So where is the problem?
    The client application recieves the image as following:
    public void run()
            try
                socket = new Socket("127.0.0.1", 2000);
                BufferedOutputStream out_file = new BufferedOutputStream(new FileOutputStream("recieved_img.png"));
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                int inputLine;
                while((inputLine = in.read()) != -1)
                    char c = (char)inputLine;
                    System.out.println(c);
                    out_file.write(inputLine);
            catch(IOException err){ err.printStackTrace(); }
        }And the server sends the image like this;
    try
              socket = server.accept();
              in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
              out = new BufferedOutputStream(socket.getOutputStream());
              out.write(25);
              while((inputLine = in.readLine()) != null)
                   System.out.println(myArrayImage.length);
              System.out.println(inputLine);
                        out.write(myArrayImage);     // Send the array of bytes
         }

  • How to convert imaq image to a 2D array without vision development module

    Hi,
    I'm looking for a way to convert an Imaq image into a regular picture (2D array) without using "Vision development module", nor saving it to a file (I need a refresh rate of about One frame per second).
    any ideas?
    thanks,
    Gilad.

    Greetings, 
    If instead of attempting to acquire the image as the raw data as per the last example, are you looking for something then like the IMAQ Image to Array? I made some research and initially I believed this VI was part of the Development Module, but I was thinking of the Array to Image VI, which is why I did not bring it up earlier.
    Finally, how exactly will you then be manipulating that array? Or will you simply be interested in displaying it? 
    Cordially;
    Simon P.
    National Instruments
    Applications Engineer

  • How to convert the record stored iin byte array to integers

    im making a simple game in j2me and i want to get the max scores and show it for each player , what i face right now that i cant convert the records which i stored in bytes to integers when i read it from file to get the max.
    thanks

    have a look at java.io.DataInputStream

  • How to convert  Wav file  in to byte array an vise vers into RMS???????????

    hi Constantinos Loizou
    i m having same problem which u were facing in last month.
    my problem i have to save .WAV file into RMS and then retreive it from RMS.
    my Code is
    Read From RMS
    RecordStore rsUser = RecordStore.openRecordStore(file,true);
    if(rsUser.getNumRecords() > 0)
    try {
    byte[] byusrinfo = rsUser.getRecord(1);
    InputStream in = new ByteArrayInputStream(byusrinfo,0,byusrinfo.length);
    p = Manager.createPlayer(in,"audio/x-wav");
    p.start();
    return true;
    catch(Exception ex) {
    ex.printStackTrace();
    return false;
    rsUser.closeRecordStore();
    catch(Exception ex) {
    ex.printStackTrace();
    return false;
    Write in RMS
    try {
    RecordStore rsUser = RecordStore.openRecordStore(file,true);
    int idata = is.available();
    byte[] exdata = new byte[idata];
    is.read(exdata);
    if(rsUser.getNumRecords() > 0) {
    rsUser.setRecord(1,exdata,0,exdata.length);
    else {
    rsUser.addRecord(exdata,0,exdata.length);
    rsUser.closeRecordStore();
    catch(Exception ex) {
    ex.printStackTrace ();
    now i have the file successfully when i retrieve it from RMS and p.reliaze() give me exception
    javax.microedition.media.MediaException: Failed to realize Player: Malformed wave media: expected 'RIFF'
    have u able to solve it. if yes then pls give me solution. or give other solution if this soution is not good
    regardz
    Hassan Mushtaq

    Well, I'm not going to give you your code on a silver platter. You'll need to put some effort in it yourself.
    So look at that available() method yourself an see if you can improve on that. Look at the api docs, there is loads of information there, and often it will give you pointers on why things are not working.

  • How do i convert an image object to a byte array ?

    Hi
    how do i convert an image object into a byte array
    early reply apperciated

    Oh sorry my method and the other method need to have the pixels from the Image passed to them which you get my using pixelgrabber:
    //create width and height variables from image
              int w = img.getWidth(this);
              int h = img.getHeight(this);
              //retrive picture from image
              int[] pix = new int[w * h];
              PixelGrabber pg = new PixelGrabber(img, 0, 0, w, h, pix, 0, w);
              try{ pg.grabPixels();
              } catch (InterruptedException ioe) {
                   System.err.println("Interrupted");
              if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
              System.err.println("image fetch aborted or errored");
              }

  • 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

  • Converting an Image object to a BufferedImage object?

    I have a BufferedImage object, bi, which I want to resize, hence:
    Image image = bi.getScaledInstance(400, 300, Image.SCALE_DEFAULT);
    Next I want to encode the resized image to JPEG format. The problem is that inorder to use the JPEGImageEncoder.encode() method, I need to pass it a BufferedImage object. I have looked through the API and cant see a way of converting the Image object to a BufferedImage object.
    Can anyone shed some light on this problem?
    Any help will be much appreciated.

    I copied + pasted the code from:
    http://java.sun.com/docs/books/tutorial/2d/problems/ind
    x.html :-)
    So you propably could use :
    int width = 400;
    int height = 300;
    Image image = bi.getScaledInstance(width, height,
    Image.SCALE_DEFAULT);
    BufferedImage bi = new BufferedImage(width, height,
    BufferedImage.TYPE_INT_RGB);
    Graphics2D biContext = bi.createGraphics();
    biContext.drawImage(img, 0, 0, null);Greets
    PuceThis works fine; but has anybody else noticed this takes an unreasonable amount of time? How to get around this?

  • How to convert a image layer to a text layer any idea? a image looks like a text in layers box

    How to convert a image layer to a text layer any idea? a image looks like a text in layers box

    You can't convert an image into a text layer.  What you can do is clip an image to a text layer so that just the image layer shows up where there is text.  Create a text layer, then above it put your image layer.  Hold down the alt/opt key and click between the two layers to clip them.

  • Converting an image object to  bufferedimage object

    Hi does anyone know how to convert an Image obj to a BufferedImage obj without casting...
    I have generated an image in an applet by rescaling a larger image but i cannot cast it to a BufferedImage as it was declared as an image type...
    thx

    Image img = setupImage(); // or however you set up your Image
    BufferedImage bimg = new BufferedImage(img.getWidth(), img.getHeight, BufferedImage.TYPE_ARGB);
    Graphics g = bimg.getGraphics();
    g.drawImage(img, 0, 0, null);

  • How to convert TIF image to Binary internal table.

    How to convert TIF image to Binary internal table

    Hi,
    this forum is for the SAP Integration Kit.
    I would first of all suggest you describe your problem in more details as you are not even describing which products you are using and second I would suggest you post it into the correct forum.
    regards
    Ingo Hilgefort

  • How to compress non-image object streams using maximum compression in acrobat x pro

    How to compress non-image object streams using maximum compression in acrobat x pro
    Please provide the screenshot if possible. Thanks!

    ZIP is the best compression for non-image streams, and it will almost certainly already have been used.

  • How to convert from image based pdf to text based pdf

    I have Adobe 9 Pro. How to convert from image based pdf to text based pdf? For example, if someone emails a scanned pdf to me, how do I convert that document into a text based pdf?

    To perform OCR, open the document and select: Document > OCR Text Recognition > Recognize Text Using OCR
    More information on the various options is in the Acrobat help doc.

  • How do I insert an object in an array?

    How can I insert an object in an array of variable size?
    I input two numbers from keyboard
    1
    2that form the following object (Pair)
    (1,2)
    how can I add such objects to an array
    private Pair s[];
    e.g.
    public PairList(int x){
    top = -1;
    s = new Pair[x];
    }//constructor
    public void getPairs()throws FullException{
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    try{
    a=input.readLine();b=input.readLine();
    }//try
    catch(IOException e){System.out.println("Can't read input");}//catch
    int x=0;
    int y=0;
    try{
    x=Integer.parseInt(a);}//try
    catch(NumberFormatException e){}
    try{
    y=Integer.parseInt(b);}//try
    catch(NumberFormatException e){}
    Pair k=new Pair(x,y);
    System.out.println(k);
    s[++top]=k; --here is my problem
    }//getPairs

    I tried making as few changes to your code as possible, but your idea should basically work. Potential problems:
    1. Doesn't allow for more input than 1 pair.
    2. By storing pair in an array, you must know the exact size of the array you will need beforehand. You might be better off storing the Pair(s) in a Vector and then converting that to an array.
    3.Your exception handlers need some work. Basically, your exception handlers put out a message or do nothing and then you continue processing. Not good.
    4. No cleanup of file resources after you have completed
    import java.io.*;
    public class PairList{
         private Pair s[];
         private int top;
         public PairList(int x){
              top = -1;
              s = new Pair[x];
         }//constructor
         public void getPairs()throws Exception{
              BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
              String a = null, b = null;
              try{
                   a=input.readLine();
                   b=input.readLine();
              }//try
              catch(IOException e){
                   System.out.println("Can't read input");
              }//catch
              int x=0;
              int y=0;
              try{
                   x=Integer.parseInt(a);
              }//try
              catch(NumberFormatException e){
              try{
                   y=Integer.parseInt(b);}//try
              catch(NumberFormatException e){
              Pair k=new Pair(x,y);
              System.out.println(k.toString());
              s[++top]=k; //here is my problem
         }//getPairs
    class Pair {
         private int xx;
         private int yy;
         public Pair(int x, int y) {
              xx = x;
              yy = y;
         public String toString() {
              return("X = " + xx + "  Y = " + yy);
    }

  • How to remove blank data from a byte array

    Hi All,
    How to remove blank data from a byte array. Suppose I created a byte array as byte[] b = new byte[8192] and i read the data as inputstream.read(b). If the data that has been received is only 1000 bytes length, how to find out how much data has been read or how to delete that blank 7192 bytes of data?
    Thanking you,
    Regards,
    Shankar.

    1) Always try to sidestep this by allocating only the necessary amount of space required...
    2) If 1 is not possible, you will have to index byte for byte how much data was read into the array which
    denotes reading byte for byte... not ideal as this is relatively slow...
    Are you reading from a file?

Maybe you are looking for

  • How to check for null values in bpel?? Please Help! very urgent!!!

    Hello Guys, I have a problem. I have an external webservice to which I have to post my request. My task is to create an Webservice and Service Assembly to which others would post request and get response. I have to create SA to deploy onto the bus. T

  • "The application iChat quit unexpectedly"; "Library not loaded"?

    Whenever I try to launch iChat, I receive "the application iChat quit unexpectedly" error. Neither "Relaunch" nor "Reset and Relaunch" fix the issue, and when I click "Report" and view the "Report Details" it gives the output enclosed below. The gist

  • My refurbished iPhone 5 display has a yellow tint?

    I got a replacement iPhone from AppleCare today, and I've got everything figured out with my new iPhone 5. When I was texting my friend, in messages I noticed the white background in the messages apphas a yellow tint to it. To make sure I wasn't seei

  • Pending Bills

    Hai FI Consultants, I am doing a report fro pending bills for all type of purchase orders. i am using the following tables EKBE, EKBZ. ekbe - for all type of movements and Grir cleared value. ekbz - import purchace orders(asset) - only goods received

  • Itunes restart automatically when i quit it

    Hello I'm running os x Lion 10.7.4 and iTunes last version 10.6.3 on an Imac 24" 2.8GHZ  core 2 duo (4go ram) early 2008 When i quit itunes, it restart automatically, impossible to stop it. It uses all my cpu too. There is no message in the console o