Sending a image over a network

Hi all,
Here is the problem. I want to send an Image from 1 computer to another computer over the internet using java... 1 computer is a server... that loads a image from harddisk or other resource (internet) and sends this to the other pc (client applet)
How do I send and read it to create an image... ObjectStream is not an options because that does not support Image objects (or am I wrong here?)
Please help
Greetingz
David

Here is one way to to do it. Read the image file as a stream of bytes, send it to the client. On the client-side, create the image from the bytes received.
Here is an example using RMI:
Loading images ad bytes on the server side:
public synchronized byte[] loadImageAsBytes(String filename)throws java.rmi.RemoteException {
      try {
        FileInputStream bis = new FileInputStream(filename);
        byte[] imageBuf = new byte[1024];
        ByteArrayOutputStream boutstream = new ByteArrayOutputStream();
        for(;;){
          int bytesread = bis.read(imageBuf);
          if (bytesread <0) {break;}
          boutstream.write(imageBuf,0,bytesread);
        byte[] pixmap =boutstream.toByteArray();
        return pixmap;
      } catch (Exception e) {return null;}
   }In this example, loadImageAsBytes() is a remote method.
Here is how you can the image on the client side:
byte[] buffer = loader.loadImageAsBytes(filename);
Image img = Toolkit.getDefaultToolkit().createImage(buffer);The loader object was created using this statement:
loader = (ImageLoader)Naming.lookup("SimpleImageServer");Note that ImageLoader is the interface that specifies the loadImageAsBytes() method.

Similar Messages

  • How do I send an Image over a socket ?

    I'm trying to get the output from my webcam and send that data out to a socket. Now the output from the webcam is running I'm just not sure how to send it out over the socket.
    Server.java
    import java.io.*;
    import java.net.*;
    public class Server {
       public static void main(String args[]) {
         ServerSocket serverSocket = null;
         boolean listening = true;
         try {
         serverSocket = new ServerSocket(1354);
         System.out.println("Listening for Connections...");
         } catch (IOException drr) {
         System.out.println("Error Listening :" + drr);
         System.exit(-1);
         try {
         while(listening)
         new ServerThread(serverSocket.accept()).start();
         } catch (IOException er) {
         System.out.println("Error Creating connection:" + er);
         try {
           serverSocket.close();
         } catch (IOException err) {
         System.out.println("Error Closing:" + err);
    }When a connection is made it will start the webcam and send the image.
    ServerThread.java
    import java.net.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.io.*;
    import javax.media.*;
    import javax.media.format.*;
    import javax.media.util.*;
    import javax.media.control.*;
    import javax.media.protocol.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import com.sun.image.codec.jpeg.*;
    public class ServerThread extends Thread {
        public static Player player = null;
        public CaptureDeviceInfo di = null;
        public MediaLocator ml = null;
        public JButton capture = null;
        public Buffer buf = null;
        public Image img = null;
        public VideoFormat vf = null;
        public BufferToImage btoi = null;
        public ImagePanel imgpanel = null;
        private Socket socket = null;
        Image blah;
        PrintWriter out = null;
        public ServerThread(Socket socket) {
         super("ServerThread");
         this.socket = socket;
        public void run() {
         try {
             out = new PrintWriter(socket.getOutputStream(), true);        
             imgpanel = new ImagePanel();
                 String str1 = "vfw:CompUSA PC Camera:0";
                 String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
                 di = CaptureDeviceManager.getDevice(str2);
             ml = new MediaLocator("vfw://0");
                try {
               player = Manager.createRealizedPlayer(ml);
                 } catch (Exception npe) {
               System.out.println("Player Exception:" + npe);
                player.start();
             Component comp;
             if ((comp = player.getVisualComponent()) != null) {
               // Grab a frame
               FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl");
               buf = fgc.grabFrame();
               btoi = new BufferToImage((VideoFormat) buf.getFormat());
               //Send the image over the socket
               out.println(btoi);
         } catch (IOException e) {
             System.out.println("It bombed:" + e);
        public static void playerclose() {
           player.close();
           player.deallocate();
      class ImagePanel extends Panel {
        public Image myimg = null;
        public ImagePanel() {
        public void setImage(Image img) {
          this.myimg = img;
          repaint();
        public void paint(Graphics g) {
          if (myimg != null) {
            g.drawImage(myimg, 0, 0, this);
      }The output I get from running the server is this:
    BufferedImage@c9131c: type = 1 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0 IntegerInterleavedRaster: width = 320 height = 240 #Bands = 3 xOff = 0 yOff = 0 dataOffset[0] 0
    Now how can I turn this into an image If this output is correct?

    HUH?
    I got the one to send the images over the network. I'm now trying to get the exact feed of the webcam and sending that over the network. This is alot more difficult to accomplish but I did see where I messed up my process of sending the images was just having to save the file then open it up put it in a byte array then send that over the network to the client. Once it was at the client i was able to re-construct it and throw it up in the frame. The only problem was lag. So this tells me it would be much more faster if instead of saving the file to send the client and having to reconstruct the image I should just send the webcam feed i used to make the image.
    eh, I guess I didn't need any help.
    Hey no offense or anything but you really have to learn how to spell better.

  • Send wav files over a network

    Hi folks,
    I need to send sound files over a network. The files I'm wanting to send are wav files. I kinda have the mechanism that sends a file, but I am not sure how to convert wav files into something that I can easily send. Do I need to convert them into bytes, serialize them...etc I don't know.
    Can anyone please point me in the right direction? An example would be very much appreciated.
    Thank you,
    E

    hi
    this is very simple
    convert voice to bytearray
    just create one server socket and client socket then connect a sockets and transmit
    download sample from
    http://javasolution.blogspot.com/2007/04/voice-chat-using-java.html

  • Need to send object instances over the network

    I found no other way to implement a switch case to cast objects on both sides to solve my problem.
    Basically I need to send objects over a network protocol based on XML, the object is sent inside XML
    converted in base64, overall encoding of XML is utf-8.
    Let's suppose in my network there are 2 peers connected via socket.
    I have multiple instances of different types on both peers but I want to keep these instances
    synchronized. If something changes on side A, side B must receive that instance and replace
    it in the correct place (just one way, from A to B).
    When I receive such instance on B I want to cast it to it's proper instance
    of it's proper type and I am scratching my head on how could I implement this without some
    sort of unique ID table and switch case.
    If I had 1 instance per type could it be done easily?
    But I need to keep in synch many instances per type.
    Is there any dynamic casting that I can trigger based on some type/instanceID information
    I could send along the object?

    I found no other way to implement a switch case to cast objects on both sides to solve my problem.
    Basically I need to send objects over a network protocol based on XML, the object is sent inside XML
    converted in base64, overall encoding of XML is utf-8.
    Let's suppose in my network there are 2 peers connected via socket.
    I have multiple instances of different types on both peers but I want to keep these instances
    synchronized. If something changes on side A, side B must receive that instance and replace
    it in the correct place (just one way, from A to B).
    When I receive such instance on B I want to cast it to it's proper instance
    of it's proper type and I am scratching my head on how could I implement this without some
    sort of unique ID table and switch case.
    If I had 1 instance per type could it be done easily?
    But I need to keep in synch many instances per type.
    Is there any dynamic casting that I can trigger based on some type/instanceID information
    I could send along the object?

  • Labeling images over a network in Bridge

    I was thinking of using Adobe Brige CS5 over a network. Mainly it would be just to see images all stored in one location on a server. Most people only have reading rights to this server. So when they open Bridge on their computer they can only view the images which is perfect. Is it possible to just have them be able to labe images on their computer fro there own use? Cant give them the writing rights. Is this possible to do.?

    Bridge is not particularily well suited for use over a network.  What you are asking would be difficult to do as it would need some kind of an interface one would have to write to act as a go between. 

  • System Image over a network

    OS X Leopard Server 10.5.6
    has anyone been able to create an image of a mac over a network. My process is this:
    netboot the source mac
    share the hard drive of the source mac with the xserver. (not the netboot drive)
    open the system image utility, it recognizes the mounted source drive.
    kick it off system image, everything works fine. However, very slow
    i kicked it off yesterday, and noticed it failed sometime lastnight.
    if it fails again, i'll post up the log.
    eventually our xserver will be in a network rack away from our office and i won't have the benefit of firewire to make an image. Is this the correct way of creating an image remotely?
    thanks,
    patrick

    You can download and install the 'System Admin Tools' to any compatible Mac client (not server). Therefore you can use another Mac to create the image on and not the server. Especially if you have a production server that provides services other than NetBoot, this will reduce it's available resources. Create the image from another Mac (with Firewire or other) using System Image Utility.

  • Sending Connection Object over the Network using RMI

    Hi,
    How can a Connection object be sent over the network and run on another JVM. I need to hold connection object to execute processes one after other, that require Oracle connection without ever connecting again. I do not have J2EE container or webserver setup to hold connection/connectionpool,but need to run the process on command line. I am using RMI infrastructure to pass parameters/return values but connection object is not serializable and connot be marshalled and failing. Please explain, if there is another way using JDK 1.4
    Sudheer

    I think that what you want to do is connect to the database on the RMI server object, then use the server object from your remote clients to execute the processes you require to rrun.

  • Sending Connection object over the network

    Hi,
    How can a Connection object be sent over the network and run on another JVM. I need to hold connection object to execute processes one after other, that require Oracle connection without ever connecting again. I do not have J2EE container or webserver setup to hold connection/connectionpool,but need to run the process on command line. I am using RMI infrastructure to pass parameters/return values but connection object is not serializable and cannot be marshalled and failing. Please explain, if there is another way using JDK 1.4
    Sudheer

    I don't believe this is possible. A connection object has a number of associated structures on the operating system, which generally makes it impossible to move. From a fundamental networking level, you also cannot, in general, cause a connection to machine1 to start communicating with machine2-- that would introduce all manner of security problems.
    Why don't you want to just create another connection on the other machine?
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • IChatAV and file transfer over wireless network

    Hi there...
    I'd like to let you in on my predicament. Firstly, a bit of background.
    I decided to buy my folks an old iMac from eBay in Australia - and pay for their broadband connection - so that I could video chat to them from the UK, and they could see my 5 year old son for the first time in 4 years. Cute, eh?
    Well, everything was working fine until I decided to go wireless in my home about 3 months ago. I have a static IP address, and purchased a nice new Airport Express to integrate into the system. I allocated my G5 iMac it's own network address (10.0.1.2), and the base station the master address (10.0.1.1). From there, the base station communicates to the router via the static IP... Sound ok?
    Anyway - NOW (or, for as long as I can recall), I CANNOT for the life of me send files over the connection. Video chat and audio chat are fine (although OCCASIONALLY it takes a few goes to be able to see THEM on my computer - I think their bandwidth isn't THAT stable at 512Kbps down and 128Kbps up) - however, the correct ports have been unblocked on the OSX firewall AND the Airport Express base station.
    And just so that you know it's not the folks' fault - I can't send documents/images over the network to friends I KNOW are competent (or, at least more competent than my parents!). There's always an error message at the receiver's end, and the file I'm attempting to send just times out.
    Has anyone any suggestions as to how I might be able to resolve this problem before I expire from old age?!?
    Your thoughts are REALLY appreciated!

    Hi Ralph
    I can see where that might be the case, but file transfer worked flawlessly BEFORE I went wireless using the same modem. The only way to unblock ports on my router is to turn NAT off - it creates a DMZ, so it permits unhindered 2-way traffic...
    It's a pretty confusing piece of kit. Maybe I should just get a Netgear anyway!
    I have a laptop on the wireless network as well, and file transfer works a treat between it and the iMac. All I can think of is that because I'm now working on a LAN, there's a blockage to get out to the "Real World" - even though it's easy for video to pass through.
    I'll check my unblocked ports again, just to be sure. I'm unfamilar with the term "Jabber" - is that what Apple decided to call one of the elements of iChat? Excuse my ignorance...!

  • Send BufferedImage over the network

    I have already successfully setup a client/server connection. The issue, is when I send the BufferedImage over the network, it says:
    "Caused by: java.io.NotSerializableException: java.awt.image.BufferedImage"
    Can someone please tell me how to fix this?

    Like the exception say, BufferedImage is not serializable. You cannot serialize it. The problem will go away if you don't try to serialize it. Of course, that doesn't answer the question you really meant to ask... which I'll leave for somebody else.

  • How can i taransfer an image over network through Sockets

    If any one have the exsperience for tranfering the image over the network by using socket plz help me immediatly

    You have to write a Server application and a Client application.
    And connect the Client to the Server.
    Then you can send whatever you want in either direction.

  • Send BufferedOutputStream content over network in the order I choose

    Hi,
    The following method send a file over the network, it sends a couple of bytes arrays, including a file.
    I need to include the byte arrays and the file array in the same output buffer, and in my code i'm reading the File first to "outFileBuffer.write(buffer, 0, len);" to get the length, and then creating another buffer with the rest of the arrays.
    If there was a way to copy the from one buffer to another i had my problem fixed.
    public void sendOrder() {
            //Enviar encomenda (ver protocolo para identificar formatação dos pacotes)
            byte[] tipo = new byte[2];
            byte[] dataLength = new byte[4];
            byte[] fileNameLength = new byte[4];
            byte[] fileName;
            byte[] fileLength = new byte[4];
            byte[] file;
            String fxName;
            int fxNameLength;
            int len;
            int fxLength = 0;
            int length;
            int BUFFER_SIZE = 1024*50;  
            byte[] buffer = new byte[BUFFER_SIZE];
            fxName = "EO10001.DAD";
            fileName = fxName.getBytes();
            //Get and Send File Block
            try{
                //Get File Stream
                InputStream is = new FileInputStream("c:\\encomendas\\" + fxName);
                //Open Output Streams to send data to server
                OutputStream out = socket.getOutputStream();
                outBuffer = new BufferedOutputStream(out);
                while ((len = is.read(buffer)) > 0){
                    outFileBuffer.write(buffer, 0, len);
                    fxLength = fxLength + len;
                    System.out.println(fxLength);
                //initialize file byte array with file length size
                file = new byte[fxLength];
                //Wrap data into ByteBuffers
                ByteBuffer tipoBB = ByteBuffer.wrap(tipo);
                ByteBuffer dataLengthBB = ByteBuffer.wrap(dataLength);
                ByteBuffer fileNameLengthBB = ByteBuffer.wrap(fileNameLength);
                ByteBuffer fileNameBB = ByteBuffer.wrap(fileName);
                ByteBuffer fileLengthBB = ByteBuffer.wrap(fileLength);
                ByteBuffer fileBB = ByteBuffer.wrap(file);
                //Order data to least significant byte first
                tipoBB.order(ByteOrder.LITTLE_ENDIAN);
                dataLengthBB.order(ByteOrder.LITTLE_ENDIAN);
                fileNameLengthBB.order(ByteOrder.LITTLE_ENDIAN);
                fileLengthBB.order(ByteOrder.LITTLE_ENDIAN);
                //Fill the arrays with the data
                tipoBB.put((byte) 0,(byte) 4);
                fxNameLength=fxName.length();
                length = 32 + fxNameLength + 32 + fxLength;
                dataLengthBB.putInt(length);
                fileNameLengthBB.putInt(fxNameLength);
                fileNameBB.put(fileName);
                fileLengthBB.putInt(fxLength);
                //fileBB.putInt();
                //Write and flush the data to Stream
                incoming.append("\n\nSending file...");
                outBuffer.write(tipo);
                outBuffer.write(dataLength);
                outBuffer.write(fileNameLength);
                outBuffer.write(fileName);
                outBuffer.write(fileLength);
                outBuffer.flush();
                outBuffer.close();
                out.close();
                outFileBuffer.flush();
                debugData(tipo, dataLength, fileNameLength, fileName, fileLength, file); //append data to JTextArea for debugging purposes
            } catch (IOException ex){
                ex.printStackTrace();
    } // close methodThanks in advance for your help, I hope I was clear.
    Regards.

    darted wrote:
    That is not contrary to what I said - FIFO - first in First out.
    Yes, your buffer stream - (not TCP/IP packet (your stream will be broken up into many packets) by the way but still they are seeing it as two separate communications.
    So, timing will be an issue since you do not want them timing your communication out.
    You are sending known sizes on everything else, so create an out buffer of the inbuffer size plus known additional then send the two to the out stream. That will hopefully prompt them to look for complete data.
    Are you sure they are not timing out your communication?
    Edited by: darted on Dec 17, 2008 2:46 PMYou are right, it's FIFO, what i meant to say is that, the same order that i put things in the buffer is the same order that goes out to the stream, so it's the order i like it to be.
    What i realize from my testing is that whatever i put in the buffer before sending it, goes all in one packet (because is a small amount of data off course, but this will always be true), so i figure, if i can put the file in the same buffer I had my problem fixed, so sending two buffers (which is what i already was doing) is not, i think, the solution i want.
    They are not timing out my communication that i know, in the log file i can see that it receives my first packet, but it says the packet is incomplete (because the file should be part of this packet) :S
    Sure their's application should be able to get around this, but that's out of my control unfortunately.
    I'm still trying to put everything else in the same buffer before sending it.

  • App imitates sending out a virus over the network

    The last time I ran the Classic App called "Farallon Ping" which came with my old Farallon NC I bought years ago was back in 2003 or 2004 and I was told by IS of the University I was attending not to run it again as the app makes it appear to be sending out viruses over the network. The app is useful as it tells me my IP address and the IP address of every computer in my domain and offers many other features some of which that are lacking in the built in OSX utilities.
    I am at a much larger University these days and I was wanting to run this app for the features but not sure if I should.
    Is this post appropriate for this group and if so what do you say?
    Thanks

    Know nothing about Farallon Ping. Would MacPing at http://74.125.93.104/translate_c?hl=en&sl=nl&u=http://dartware.com/downloads/leg acy.html do the same thing?
     Cheers, Tom

  • RE: Sending jpg bytes over a server

    I had another topic but it has not been answered for a couple days so I guess I will clarify my problem more.
    I'm sending my image over a server, Client->Server->Client.
    My sending and receiving works but I get the image and it cannot be displayed.
    Sending
    try{
                  FileInputStream fis = new FileInputStream("picture.jpg");
                  byte[] buffer = new byte[fis.available()];
                  fis.read(buffer);
                  return buffer;
             }catch(Exception e){
                  System.out.println("Loading Image error");
             }Receiving
             try{
                  FileOutputStream fos = new FileOutputStream("received.jpg");
                  fos.write(image);
                  ImageIcon display = new ImageIcon("received.jpg");
                  clientDisplayPicture=new JLabel(display);
             }catch(Exception h){
                  System.out.println("Problem receiving");
             }Am I packaging it wrong? The received image is 0bytes. Thanks in advance!

    Here you are ignoring the result of the read() method.Meaning?
    Here you are not telling us how the incoming data got into 'image'.I put the bytes of the image into an object and passed it over the network.
        public void displayPicture(String from, byte[] image, boolean a, boolean b){
             try{
                  FileOutputStream fos = new FileOutputStream("received.jpg");
                  fos.write(image);
                  fos.close();
             }catch(Exception h){
                  System.out.println("Problem receiving");
        public byte[] getImage(){
             try{
                  FileInputStream fis = new FileInputStream("picture.jpg");
                  File f = new File("picture.jpg");
                  int bsize = 1375;
                  byte[] buffer = new byte[bsize];
                  fis.read(buffer);
                  fis.close();
                  return buffer;
             }catch(Exception e){
                  System.out.println("Loading Image error");
             return null;
        }EDIT: Thanks, got it working, the above worked. THANKS!
    Edited by: Krytical on Aug 10, 2008 12:09 AM

  • Sending an Image

    Hello!
    Usually, when I use networking (which is rare) PrintWriter fulfills my needs. But in this case I need to send a BufferedImage over a network, and I don't think PrintWriter would work. Does somebody know what class I could use?
    Thanks!

    I realize this. Here's the pseudo code of what I'm trying to accomplish:
    1. Get the image to be sent.
    2. Get the data as an array of bytes.
    3. Use BufferedOutputStream to send the bytes.
    The problem with my code is with #2. I can't seem to find a way to convert an image into an array of bytes. The above code is the closest I have ever gotten.
    Any suggestions?
    here my suggestion
    1. get image from file or what?, if you want to get image from file then you should use fileInputStream like this :
    public byte[] readFile(String fileName){
           ByteArrayOutputStream bos = new ByteArrayOutputStream();                   
            try{
                fis = new FileInputStream(sourceFile);
                int d;
                while((d=fis.read())!=-1){
                   bos.write(d);               
                System.out.println("LOAD FILE COMPLETED");
            }catch (IOException e){
            //nothing to do
            }catch (StringIndexOutOfBoundsException e){
                System.out.println("BLA2");
            return bos.toByteArray();
       }2. then you can send bos that already come byteArray like this :
    public void sendChunkFile(byte[] fileByte) {
            DataOutputStream os;
            int off = 0;
            boolean endFile = false;
            while (!endFile) {
                if ((off+chunkSize)>=fileSize) {
                    endFile = true;
                    chunkSize = fileSize - off;
                    os.write(fileByte,off,chunkSize);
                    off = off + chunkSize;    
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
            if (endFile){
                System.out.println("FILE Sent");
                chunkSize = CHUNK_SIZE;
       }maybe that will help you
    Edited by: nDeh-tEa on Oct 6, 2007 4:38 PM

Maybe you are looking for

  • Skipping problem with ipod

    I have another problem with my 30G ipod video. It skips certain songs, not entirely, but partway through. For instance, there is a song that it will play for 15 sec, and then skip to the next one. It is always the same songs and it skips at the same

  • Stacked Bar Chart with data from a Web Service

    Hi, I'm working on Dashboard Design (version 14.0.1.287) and I'm trying to create a chart linked to data from a webservice. With a Year in input, my webservice gives an Amount per Cities and Products Data retrieved look like this (Sheet1) : Paris    

  • Chart label length clipping problem

    I have a generic chart rendering app.  It works fine for most charts, but I am getting some really wierd results when I use a logAxis.  It is clipping the chart on the right side.  Does anyone know how to fix this problem? <mx:Panel xmlns:mx="http://

  • Mail not showing mail

    Hi, My Mail has been working great.. until i bought an iPhone4. I don´t know if this is the reason, but when i synced my iPhone from iTunes my mail account only shows NOTES. I deleted the mail account (my schools mail, imap) and reconnected the mail

  • Songs Unmatched by iTunes Match

    A number of songs in my library remain unmatched by iTunes Match and were uploaded instead. However, I know that many of the songs that were uploaded are available in iTunes (such as Star Wars tracks). Also, some albums were partially matched like Ho