I am trying to transmit an Image object through a Socket connection in Java. The only thing I may be missing is how to get an image size in bytes so I know how many bytes are being transferred over the Socket.

I have the ServerSocket and Client working transferring data, and I have a cut-paste image working from a client Applet, and I have a Java program that saves Images to disk as JPEG/PNG.

How do you get the byte size of an Image object in Java?... or do you know of source code to a program that transferes images through Sockets?

Thanks,
Jon

Recommended Answers

All 16 Replies

Member Avatar for ede

ı couldn't understand why you wanna get image byte size. as a result
images are also files. so you can trnsfer you images as a byte streams.
just read image file with an inputstream and write it to socket outputstream.


InputStream input=new FileInputStream("image.png");
byte[] buffer=new byte[1024];
int readData;
while((readData=input.read(buffer))!=-1){
socketOutput.write(buffer,0,readData);
}

I cant read from a file stream, because the client application is an Applet (browser applet) in this client/server image transrfer program. You can't access files from an Applet in Java.

I can paste an Image into the Applet and cast it to a BufferedImage object, but I don't know how to send the BufferedImage object over a Socket. I need the size of the BufferedImage object so I can notify the server Java application of how many bytes it is to expect on the receiving end.

Jon

I've had the same problem as you, and finally my solution was the next one:

BufferedImage bIResult = null;
// Fill your bufferedImage
ByteArrayOutputStream bos = new ByteArrayOutputStream();
boolean resultWrite = ImageIO.write(bIResult, "PNG", bos);
byte[] imageInBytes = bos.toByteArray();
int length = imageInBytes.length;

Sincerily,

Isabel

In client applet i have a code

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import javax.imageio.*;
public class test_client extends Applet {
    public void init() {
	Button b = new Button("submit6");
	b.addActionListener(new ActionListener() {
	  public void actionPerformed(ActionEvent ae) {
	     showStatus("button pressed");
             try {
		BufferedImage bi =new BufferedImage(100,100,BufferedImage.TYPE_INT_ARGB);
		Graphics2D g2 = bi.createGraphics();
            Graphics g = getGraphics();
		g.setColor(Color.BLUE);
		g.drawLine(100,100,200,200);
            g2=(Graphics2D)g;   
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ImageIO.write(bi,"JPEG",baos);
		byte[] buf = baos.toByteArray();
                URL url = new URL(http://10.70.70.1:8080/servlet/send_testclient");
                HttpURLConnection con =(HttpURLConnection)url.openConnection();
            
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/octet-stream");   
		OutputStream os = con.getOutputStream();
		os.write(buf);
		os.flush();
		os.close();
            InputStream is = con.getInputStream();
		int c;
		while ((c = is.read()) != -1)
		  System.out.write(c);
		System.out.println();
		is.close();
		//os.close();
		con.disconnect();
	    } catch (Exception e) {
		 showStatus(e.toString());
            // System.out.println(e);   
	    }
	 }
      });
      add(b);
   }
}

I dont know how to get the image data in server side( servlet) and store as jpg pr png file.

please help me regarding this.

i need server side code.

Thanks in advance for helping me

anyone is available to help me:(

Why don't you Google "Java File Upload" and send a normal file upload requesst.

In client side I couldnt have image file.

Only I have Byte Array. I need to send to server( servlet) then i ll store it to jpeg file.

I tried the servlet code like this

InputStream in = req.getInputStream();
            int count;
	    byte[] buffer = new byte[8192];
            FileOutputStream fis = new FileOutputStream("new.jpg");
	    while ((count = in.read(buffer)) > 0){
		fis.write(buffer, 0, count); 
	        fis.flush();
            }
	    fis.close();

But i didnt find any file name as new.jpg in my server.

Please help me

Do what I suggested in the post. On a fileupload the server gets an inputstream. How that inputstream originates doesn't matter. Investigate "File Upload" streams. Both how to receive one in a Servlet, and how to initiate one using an HttpUrlConnection, and your problem is solved.

Thanks for ur reply.

I am new java and servlet.

If u know abt how to store image into server.

Please help me.

thanks

I.E.

You: "Write the code for me."

Me: "NO!"

There is a wealth of information on doing file uploads out there. I do not have an example in front of me, so to give you one I would have to search (Google) for one. And, if someone has to do that anyway, it just as well be you, as it is your assignment.

As far as your code, from your last post goes, the actual error message would help. Otherwise your "new.jpg" file will be written in the current working directory of the Application server, and that can vary depending on how your server was started. Did you try running a find to see if you could find it?

Ok thanks for ur reply

In client side Applet to create an image and send it to the HTTP server:

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
public class test_client extends Applet {
       public void init() {
	Button b = new Button("submit");
	b.addActionListener(new ActionListener() {
	  public void actionPerformed(ActionEvent ae) {
	     showStatus("button pressed");
             try {
		BufferedImage bi =new BufferedImage(100,100,BufferedImage.TYPE_INT_ARGB);
		Graphics2D g2 = bi.createGraphics();
                Graphics g = getGraphics();
		g.setColor(Color.BLUE);
		g.drawLine(100,100,200,200);
                g2=(Graphics2D)g;   
		URL url = new URL("http://10.70.70.1:8080/servlet/send_client");
                HttpURLConnection con =(HttpURLConnection)url.openConnection();
            	con.setDoInput(true);
		con.setDoOutput(true);
		con.setRequestMethod("POST");
                con.setRequestProperty("Content-Type", "image/jpeg");   
		ImageIO.write(bi,"JPEG",con.getOutputStream());
		con.disconnect();
	    } catch (Exception e) {
		 showStatus(e.toString());
           }
	 }
      });
      add(b);
   }
}

In server side(servlet): try to store the coming image to file.

import java.net.*;
import java.io.*;
import java.util.*;
import java.lang.*;
import java.lang.Object;
import javax.servlet.*;
import javax.servlet.http.*;
public class send_client extends HttpServlet {
     public void doPost(HttpServletRequest req, HttpServletResponse res)
                   throws ServletException, IOException
     {      
	 try{
            InputStream in = req.getInputStream();
            int count;
	    byte[] buffer = new byte[8192];
            ServletContext servletContext = getServletContext();
            String file = servletContext.getRealPath("new.jpg");
            FileOutputStream fis = new FileOutputStream(file);
	    while ((count = in.read(buffer)) > 0){
	    fis.write(buffer, 0, count); 
	    fis.flush();
            }
	    fis.close();
	 }
	 catch (Exception e)
	 {
		e.printStackTrace();
	 }
     }
}

But I dont know much in java.

Please correct me where I am doing wrong.

I still don't see what error is or is not happening.

What error are you getting? What is getting written into the file (soemthing is, if you are not getting an error.

Am not getting any error. But i didnt get file. I searched all directory. But file is not available.

Thanks for your reply.

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletException;
import java.io.*;

public class IShareServer extends HttpServlet {
	
   public void doPost(HttpServletRequest req,HttpServletResponse res)
    {      
      try
         {
    		  DataInputStream fromClient = new DataInputStream( req.getInputStream() );
    		  ByteArrayOutputStream baos=new ByteArrayOutputStream(Integer.parseInt(req.getParameter("LEN")));
    		  byte[] buff = new byte[1024];
    		  int cnt = 0;
    		  while( (cnt = fromClient.read( buff )) > -1 ) 
    		  {
    			  baos.write(buff, 0, cnt );
    		  }
    		  baos.flush();
    		  byte [] check=baos.toByteArray();
         saveimage(baos.toByteArray());
    		    baos.close();
    		    fromClient.close();
    		    res.setContentType("text/html");
    		    ServletOutputStream out = res.getOutputStream();    		  
    		    out.flush();
    		    out.close();
    	        }
        catch(Exception e) { e.printStackTrace();  }
   	}

  private void saveimage(byte [] buf)
   {
	 String fileName = "D:/temp1/ServletImage.jpg";
	 String path = fileName;
	 try
	 	{
	      File yourFile = new File(path);
	  	  FileOutputStream toFile = new FileOutputStream( yourFile );  
	  	  toFile.write(buf);        
	  	  toFile.flush();
	  	  toFile.close();
	  	  
	  	}
	 catch (Exception e) { 		}
  }
  
}

I cant read from a file stream, because the client application is an Applet (browser applet) in this client/server image transrfer program. You can't access files from an Applet in Java.

I can paste an Image into the Applet and cast it to a BufferedImage object, but I don't know how to send the BufferedImage object over a Socket. I need the size of the BufferedImage object so I can notify the server Java application of how many bytes it is to expect on the receiving end.

Jon

You can access files from an applet in java with signed applets or policy based permission.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.