How to send a bufferedImage Object

m trying to send bufferedImage from one computer to another via TCP/IP socket using following code...
ObjectOutputStream writer = new ObjectOutputStream(socket.getOutputStream());
writer.writeObject(<bufferedImage-Object>);
writer.flush();
but it gives an exception saying something it is not serializable.
Can somebody suggest a way to send the object?
Regards
Deewa

Hello there!
Have a look at this:
//The Server
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.awt.image.*;
import java.awt.event.*;
import java.net.*;
* TheServer.java
* Created on 29. Juli 2003, 11:19
* @author  Darimont
public class TheServer extends javax.swing.JFrame {
    private ServerSocket ss = null;
    private Socket s = null;
    private Thread serverThread = null;
    private BufferedImage bimg = null;
    private int[] pixarray = null;
    private PixelGrabber pg = null;
    /** Creates new form TheServer */
    public TheServer() {
        initComponents();
        loadImage();
    private void startServer(){
        if(serverThread == null){
            serverThread = new Thread(new myServer());
            serverThread.start();
    private void loadImage(){
        MediaTracker mt = new MediaTracker(this);
        try{
            bimg = javax.imageio.ImageIO.read(new File("c:/Beispiel1.jpg"));
        }catch(IOException ioe){
            ioe.printStackTrace();
        mt.addImage(bimg,0);
        try{
            mt.waitForAll();
        }catch(InterruptedException ie){
            ie.printStackTrace();
        mt = null;
        //Imagepixels to Array -->
        //My Imagesize is 100 x 100 Pixels so there are 10000 Pixels
        pixarray = new int[10000];
        pg = new PixelGrabber((Image)bimg,0,0,bimg.getWidth(),bimg.getHeight(),pixarray,0, 100);
        try{
            pg.grabPixels();
        }catch(InterruptedException ie){ie.printStackTrace();}
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        getContentPane().setLayout(new java.awt.GridBagLayout());
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
        jPanel1.setMinimumSize(new java.awt.Dimension(400, 300));
        jPanel1.setPreferredSize(new java.awt.Dimension(400, 300));
        getContentPane().add(jPanel1, new java.awt.GridBagConstraints());
        jPanel2.setMinimumSize(new java.awt.Dimension(400, 50));
        jPanel2.setPreferredSize(new java.awt.Dimension(400, 50));
        jButton2.setText("Start Server");
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jButton2MousePressed(evt);
        jPanel2.add(jButton2);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        getContentPane().add(jPanel2, gridBagConstraints);
        pack();
    private void jButton2MousePressed(java.awt.event.MouseEvent evt) {
        // Add your handling code here:
        startServer();
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
        System.exit(0);
    public void paint(Graphics g){
        super.paint(g);
        if(bimg !=null)
            jPanel1.getGraphics().drawImage(bimg.getScaledInstance(bimg.getWidth(),bimg.getHeight(),Image.SCALE_FAST),0,0,bimg.getWidth(),bimg.getHeight(),this);
     * @param args the command line arguments
    public static void main(String args[]) {
        new TheServer().show();
    class myServer implements Runnable{
        ObjectOutputStream oos = null;
        public void run() {
            try{
                ss = new ServerSocket(8888);
                System.out.println("Server started!");
                while((s=ss.accept())==null)
                    Thread.currentThread().sleep(100);
                System.out.println("Connected");
                BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
                oos = new ObjectOutputStream(bos);
                oos.writeObject(pixarray);
                oos.close();
                s.close();
                s= null;
                ss.close();
                ss = null;
                System.out.println("Connection closed");
            }catch(IOException ioe){ ioe.printStackTrace();
            }catch(InterruptedException ie) { ie.printStackTrace();
            } //catch(SocketException se){ se.printStackTrace(); }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    // End of variables declaration
}// The Client
import java.awt.*;
import java.net.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.*;
* TheClient.java
* Created on 29. Juli 2003, 12:08
* @author  Darimont
public class TheClient extends javax.swing.JFrame {
    private Image img = null;
    private Socket s = null;
    private int[] imga = null;
    private Thread clientThread  = null;
    /** Creates new form TheClient */
    public TheClient() {
        initComponents();
    public void start(){
        if(clientThread ==null){
            clientThread = new Thread(new theClient());
            clientThread.start();
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        getContentPane().setLayout(new java.awt.GridBagLayout());
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
        jPanel1.setMinimumSize(new java.awt.Dimension(400, 250));
        jPanel1.setPreferredSize(new java.awt.Dimension(400, 250));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        getContentPane().add(jPanel1, gridBagConstraints);
        jPanel2.setMinimumSize(new java.awt.Dimension(400, 50));
        jPanel2.setPreferredSize(new java.awt.Dimension(400, 50));
        jButton1.setText("Get Image");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jButton1MousePressed(evt);
        jPanel2.add(jButton1);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        getContentPane().add(jPanel2, gridBagConstraints);
        pack();
    private void jButton1MousePressed(java.awt.event.MouseEvent evt) {
        // Add your handling code here:
        start();
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // Add your handling code here:
    public void paint(Graphics g){
        super.paint(g);
        if(img!=null)
            jPanel1.getGraphics().drawImage(img,0,0,img.getWidth(null),img.getHeight(null),this);
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
        System.exit(0);
     * @param args the command line arguments
    public static void main(String args[]) {
        new TheClient().show();
    private void resampleImage(int[] imageArray){
        img = createImage(new MemoryImageSource(100,100,imageArray,0,100));
    class theClient implements Runnable{
        ObjectInputStream ois = null;
        BufferedInputStream bis = null;
        public void run() {
            try{
                s = new Socket("localhost",8888);
                if(s != null){
                    bis = new BufferedInputStream(s.getInputStream());
                    ois = new ObjectInputStream(bis);
                    imga = (int[])ois.readObject();
                    if (imga != null){
                        resampleImage(imga);
                        jPanel1.getGraphics().drawImage(img,0,0,img.getWidth(null),img.getHeight(null),jPanel1);
            }catch(IOException ioe){ ioe.printStackTrace();
            }catch(ClassNotFoundException cnfe){ cnfe.printStackTrace();
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    // End of variables declaration
}Have a nice day!
bye Tom

Similar Messages

  • How to create a BufferedImage object using a .png file on harddisk

    For some application of JFreeChart I want to create a BufferedImage object from png file on harddisk.
    Can anybody tell me how to achieve this?
    Thanks in advance.

    See [this thread|http://forum.java.sun.com/thread.jspa?threadID=5144115].

  • How to send a Connection Object via CORBA

    Hi.
    I've got a question.
    How can I send a java.sql.Connection object
    using CORBA to a client? Tried to use a class
    MyConnection extending org.omg.CORBA.portable.ObjectImpl
    as a wrapper class. Didn't work.
    When a request was invoked for a Connection,
    no object was send. On client side an error occured:
    code 202 completed:maybe.
    In the IDL we used:
         typedef Object MyConnection;
         interface ConnectionPool{
              MyConnection getCon();
              void freeCon(inout MyConnection c);
    We were suggested to use structures. But ain't it
    inventing java again?
    Can anyone help us?
    Thx anyway.

    Try inserting it into an Any object and sending the any object over the IDL, the client can then extract the connection object.
    You might have to typedef the Connection object in the IDL to generate the helper class.
    /P/

  • How to Pass a BufferedImage? Client - Server

    Please Help!
    I've been trying to figure out how to send a BufferedImage from my client program to the server program. I'm using a socket to create the connection. The client draws into a BufferedImage and then it is sent to the server to be saved as a JPG file. I've been able to create the image if I do it locally but since a BufferedImage is not serializable I can't do this the same way with the server. So how do I get my BufferedImage from the client to the server in a manner that I can then save it as a JPG on the server? Code examples would be very much appreciated!!!
    Thanks!
    Ryan

    I guess I'm not understanding what your saying. I just need a way to get what the user draws into a jpg on the server. I have been using sockets and streams but nothing I try really seems to work. Right now I am doing this:
    Client:
    Socket client = new Socket( InetAddress.getByName( "localhost" ), 5000 );
    ObjectOutputStream output = new ObjectOutputStream( client.getOutputStream() );
    ObjectInputStream input = new ObjectInputStream( client.getInputStream() );
    try {
    ByteArrayOutputStream imageOut = new ByteArrayOutputStream();
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder( imageOut );
    imageOut.flush();
    encoder.encode( sig.getImage() );
    byte[] image = imageOut.toByteArray();
    output.writeObject( image );
    Server:
    public void runServer() {
    ServerSocket server;
    Socket connection;
    try
    server = new ServerSocket( 5000, 100 );
    while ( true ) {
    connection = server.accept();
    output = new ObjectOutputStream(
    connection.getOutputStream() );
    input = new ObjectInputStream(
    connection.getInputStream() );
    ObjectOutputStream toFile = new ObjectOutputStream(
    new FileOutputStream( f ) );
    ByteArrayInputStream inStream =
    new ByteArrayInputStream( (byte[]) input.readObject() );
    JPEGImageDecoder decoder =
    JPEGCodec.createJPEGDecoder( inStream );
    BufferedImage sigImage = decoder.decodeAsBufferedImage();
    JPEGImageEncoder encoder =
    JPEGCodec.createJPEGEncoder( toFile );
    encoder.encode( sigImage );
    toFile.flush();
    output.close();
    input.close();
    connection.close();
    toFile.close();
    I imagine I have very ugly looking code here but I've been trying to make something work. My code does create the file but it is not a recognizable JPG file.
    Ryan

  • Sending an InetAddress-object via udp

    hi there!
    i'm developing a videostream server/client application. client is an applet. what i want to do is this:
    since an applet has to be signed in order to perform dns-lookups, i want to work around that.
    since the applet has to request the stream anyway and therefore connects the server sending udp-
    packets, my idea was to let the server send back the clients IP/hostname as an InetAddress-object
    inside a udp packet.
    i tried the following:
    info: byte[] buf = new byte[256];
    on server:
    InetAddress address = packet.getAddress();
    buf = address.getAddress();
    packet = new DatagramPacket(buf, buf.length, address, port);
    socket.send(packet);
    on client:
    socket.receive(packet);
    byte[] temp = packet.getData();
    source = InetAddress.getByAddress(temp);
    System.out.println(source.toString());
    the system.out returns this: &#305;�A)
    or other unreadable stuff, depending on the ip-address of the client.
    i think, this has something to do with the conversion to/from bytearray, doesn't it?
    can anyone show me how to send an InetAddress-object so that i get an
    InetAddress-object out at the client side?
    thanks in advance!
    you can earn some bucks, too!
    greets
    honfrek

    hi there!
    thanks for your help. i got it figured out now.
    now it works like this:
    on server:
    InetAddress address = packet.getAddress();
    buf = address.getAddress();
    byte[] newbuf = new byte[buf.length];
    newbuf = buf;
    packet = new DatagramPacket(newbuf, newbuf.length, address, port);
    socket.send(packet);
    on client:
    byte[] newbuf = new byte[4];
    packet = new DatagramPacket(newbuf,newbuf.length);
    socket.receive(packet);
    source = InetAddress.getByAddress(packet.getData());
    i made 2 mistakes:
    - i converted the InetAddress to a string
    - the length of the byte[] was too big. i had a bunch of zeroes at the end

  • How to send data to bam data object through java code

    how to send data to bam data object through java code

    I've made a suggestion in other thread: https://forums.oracle.com/thread/2560276
    You can invoke BAM Webservices (Using Oracle BAM Web Services) or use JMS integration using Enterprise Message Sources (http://docs.oracle.com/cd/E17904_01/integration.1111/e10224/bam_ent_msg_sources.htm)
    Regards
    Luis Fernando Heckler

  • How to send multiple objects in a ObjectOutputStream

    1) I need to get more than one text field and send it to the servlet.
    2) How do I keep the Objects seperate in the servlet when they get inputed. I have to so I can sabe them to seperate variables.
    Applet Code
    URL url = new URL("http://www.mysite.com/servlet/Hello");
    URLConnection servletConnection = url.openConnection();
    servletConnection.setDoInput(true);
    servletConnection.setDoOutput(true);
    servletConnection.setUseCaches(false);
    servletConnection.setDefaultUseCaches(false);
    servletConnection.setRequestProperty("Content-Type","application/octet-stream");
    ObjectOutputStream out = new ObjectOutputStream(servletConnection.getOutputStream());
    //Gets data from text field
    out.writeObject( (Object) cusNum.getText() ); //(Object)
    // I need to get more than one text field and send it to the servlet.
    out.flush();
    out.close();Servlet Code
    ObjectInputStream inputFromApplet = new     ObjectInputStream(request.getInputStream());
    String fromApplet = (String) inputFromApplet.readObject();
    inputFromApplet.close();

    //Gets data from text fieldNo, this gets data from text field and writes it to the output.
    out.writeObject( (Object) cusNum.getText() ); //(Object)So that writes one object.
    // I need to get more than one text field and send it to the servlet. So do that.
    String fromApplet = (String) inputFromApplet.readObject();Here you have read one object. If you want to read another, do so.

  • How to send nested object collection to PL/SQL Procedure as an Input param

    How to send nested object collection to PL/SQL Procedure as an Input parameter.
    The scenario is there is a parent mapping object containing a collection(java.sql.Array) of child objects.
    I need to send the parent object collection to PL/SQL procedure as a input parameter.
    public class parent{
    String attr1;
    String attr2;
    Child[] attr3;
    public class Child{
    String attr1;
    SubChild[] attr2;
    public class SubChild{
    String attr1;
    Urgent!!!
    Edited by: javiost on Apr 30, 2008 2:09 AM

    javiost wrote:
    How to send nested object collection to PL/SQL Procedure as an Input parameter.There are a few ways to do this, all of which likely depend on the particular database you're using.
    Urgent!!!Not to me...

  • How can we send a collection object to server?

    Hi All
    I am beginner in Flex. I have an assignment to do, plz help
    in this.
    How can we send a collection object to server?
    Means:
    I have a list of user details in a grid.
    And if i want to add a new User or edit a existing user
    details then i don’t want to send a request every time.
    Instead of i want to keep adding new User only in front side
    i.e. in the grid
    And finally i will send a single request with all the Users
    details.
    can it be possible ? If possible please help me.
    Thanks in advance

    Actually, the best way to do is using amfphp but since you
    are new to flex it might be a bit confusing if you dont know php.
    check here for amfphp:
    http://www.amfphp.org/
    you can also traverse through the arraycollection and create
    and xml. (this part is basic programming). Then you can send it to
    server using a post.
    For that think check the liveDocs for classes:
    HTTPService
    and
    URLLoader.

  • How to send object by NetStream?

    Hi, I have question about using Cirrus in real time game developed. I want to create a game in which each player will be able to move a character using the arrow keys. And here comes my question.How do I continuously transfer an object or variable via NetStream. Should I use the send() method (when a player is in motion), or maybe it's possible to send and receive an object using publish() and play().
    I spent a lot of time looking for solutions on the internet, but with no succes. Everything that I've found was about transmission of audio and video (attachAudio() and attachVideo()), I need a method such as attachObject(), which could continuously send for example player's position.
    I found P2PGameLibrary on Tom Krcha's site (www.flashrealtime.com). Unfortunately, it is in the  .swc file and when I use FlashDevelop to open it, it shows only the model of classes and methods. If I could see the entire code, I could study it and maybe it would solve my problem.
    If someone could give an example of how to send objects/variables by NetStream, I would be grateful.
    swO_orn

    Thanks for fast answer.
    Yes I have build a simple chat p2p using only NetGroup, and sending messages by method post(). The one "bad thing" I nothiced is delay. I got about 500ms. That's too much for real time games.
    I have watch some tutorials on Tom Krcha's blog and they said I should build full mesh of direct connections of all users to make P2P game.
    Let's say I want to have 6 players sending and receiving info in game. What's the best way to transfer data between them? NetGroup.post() or NetStream.send() or maybe another?
    PS: Please give me an example how to receive data in NetStream if data was transfered by send() method.
    Doc says :
    send(handlerName:String, ... arguments):void
    How do I start handler on receiver app?

  • How to know method name dynamically with sender or EventArgs object

    Hello All,
    I am working in ASP.NET. I wanna log method name in log file whenever that method is executed. e.g.
    protected void Page_Load(object sender, EventArgs e)
    Trace.Log("Page_Load start");
    Trace.Log("Page_Load end");
    protected void Method2(object sender, EventArgs e)
    Trace.Log("Method2 start");
    Trace.Log("Method2 end");
    Trace.Log() is use to log my string in log files at D:\. Now, here I have hard coded Method name in Trace.Log(). But, now I want to fetch method name via c# code. Can we achieve it via sender or EventArgs object?
    Please assist.
    Thanks, Chintan

    Hello Chintan,
    You can get class name through reflection as it gets STATIC info about the component.
    However, to get the line number of an exception, which is a run time parameter, you cannot use reflection.
    I actually have not tried this before but, given it did not work for you in the web part class, you may try the below code in your *.ascx.cs user control used by your visual web part.
    //To Retrieve class name use this line:
    string className = this.GetType().FullName;
    // To retrieve other parameters including line number
    try
    TestFunction();
    catch (Exception ex)
    StackTrace st = new StackTrace(ex, true);
    StackFrame[] frames = st.GetFrames();
    // Iterate over the frames extracting the information you need
    foreach (StackFrame frame in frames)
    string stkFrame = string.Format("{0}:{1}({2},{3})", frame.GetFileName(), frame.GetMethod().Name, frame.GetFileLineNumber(), frame.GetFileColumnNumber());
    For more info, please refer to this
    post.
    THosE wHo doN'T apPreCiATe LiFe, DOn't DeSerVe iT

  • How to send timer job email to "assigned to" feild value in a task list?

    Hi All,
    How to send timer job email  to "assigned to" field value in a task list if due date is after two days from now?

    Create a SharePoint Designer Workflow and use "pause until date" option when an new item is created/update.
    Using Server Object model, I believe you can create the timer job from item event receiver.
    --Cheers

  • How to send the spool output to the specific user during ALE distribution

    Hi All
    In ALE internal order Configuration done by BAPI Method SAVEREPLICA Business object BUS2075whenever user changed the internal order which is moved to the destination system because of change data setting in data element fields.
    I want to know how to send the spool output of the changed internal order to the specific user during ALE distribution.
    Please help me to reslove the above issue
    Thanks & Regards
    KRISHGUNA

    Solved by myself

  • HELP!!! - How to send a file to a server?

    How to send a file(as it is) to the server i'm connected to, if i have access to the output-stream?

    Ummm read the APIs of anything you don't understand. Documentation is your friend, I hope you are not being lazy. But I'm in a good mood so here:
    // Make sure you try to catch any IOExceptions
    // Code expanded for clarity;
    OutputStream yourOutputStream = getYourOutputStream; // You said you can get the outputstream to the server/socket. I assume you made a connection.
    BufferedOutputStream bos = new BufferedOutputStream(
    yourOutputStream ); // Always a good idea to use buffers
    // Your object is your file
    File yourObject = new File("blabla.jpg");
    FileInputStream fis = new FileInputStream(yourObject);
    byte[] b = new byte[1024]; // A good size read
    while( fis.read(b) != -1){// read 1024 bytes into array at a time, returns -1 at end of file
       bos.write(); //write to the server
    fis.close(); // close the inputstream
    yourObject = null; // help the gc
    bos.flush(); // flush the buffer, close does this, but it is good form
    bos.close(); // close the output to the server--Thunder
    PS - The Duketer is in!

  • How to send PDF file to XI

    Hi All:
    I need to send <b>pdf</b> file to SAP XI, can I achive it using FILE adapter??
    If not with File adapter then please let me know how I can send it to XI?
    Thanks
    Aditya

    Hey
    do you wnat to do some mapping in XI or simple transfer the file to the receiver system?
    if its simple transfer then do a bypass scenario without any IR objects
    /people/william.li/blog/2006/09/08/how-to-send-any-data-even-binary-through-xi-without-using-the-integration-repository
    Thanx
    Ahmad
    Message was edited by:
            Ahmad

Maybe you are looking for

  • How to write/insert lines in a file from top

    I am opening a writing to a file as follows: (part of the code which does so) FileOutputStream file; // declare a file output object PrintStream r; file = new FileOutputStream("filename") + ".properties",true); r = new PrintStream( raj); r.println (

  • Pick list- Re-print

    hi- I have already printed a pick list for delivery. Accidently the Document got shredded. I want to print the Pick list again. Any suggestions. Steps: I did go to VL02n and try to use the functionality Picking out at header level, but the area is gr

  • PSTN Call progress indicator

    Hi, I have a set-up where call comes in for prompting and on selection of an option is sent out to an external IVR. The call-flow: PSTN -> VoiceGW -> CVP -> ICM -> CUCM Directory Number -> Call FWD to PSTN# -> VoiceGW. At the external IVR, there is a

  • Blogging Option for Muse: Adobe Muse and Rebel Mouse = Love

    I love the speed of Muse and the ablity to get up and running fast. My hold out from bringing mysite to Muse was the lack of a blogging option. They are a few work arounds, but I've found my wordpress replacement. Rebel Mouse. I won't show my Muse bu

  • Cant select php as a file type

    When opening a new file i can no longer select php as the file type. The site is set as php/mysql but nothing. any ideas