Downloading & Uploading Images Tutorial

Advertisements


In this chapter we are going to see how you can download an image from internet , perform some image processing technique over that image and then again upload that image to a server.

Downloading

In order to download an image, we are going to use java URL class which can be found under java.net package. Its syntax is given below:

String website = "http://tutorialspoint.com";
URL url = new URL(website);				

Apart from the above method , there are other methods available in URL class which are listed below:

SNMethods with Description
1public String getPath()
Returns the path of the URL.
2public String getQuery()
Returns the query part of the URL.
3public String getAuthority()
Returns the authority of the URL.
4public int getPort()
Returns the port of the URL.
5public int getDefaultPort()
Returns the default port for the protocol of the URL.
6public String getProtocol()
Returns the protocol of the URL.
7public String getHost()
Returns the host of the URL.

Example

The following example demonstrates the use of java URL class to download an image from internet.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

public class Download {

   public static void main(String[] args) throws Exception {
      try{
         String fileName = "digital_image_processing.jpg";
         String website = 
		 "http://tutorialspoint.com/java_dip/images/"+fileName;
         System.out.println("Downloading File From: " + website);
         URL url = new URL(website);
         InputStream inputStream = url.openStream();
         OutputStream outputStream = new FileOutputStream(fileName);
         byte[] buffer = new byte[2048];
         int length = 0;
         while ((length = inputStream.read(buffer)) != -1) {
            System.out.println("Buffer Read of length: " + length);
            outputStream.write(buffer, 0, length);
         }
         inputStream.close();
         outputStream.close();
        }catch(Exception e){
           System.out.println("Exception: " + e.getMessage());
        }
   }
}

Output

When you run the above example, following output screen would appear.

Downloading & Uploading Images Tutorial

It would download the following image from server.

Downloading & Uploading Images Tutorial

Uploading

Now we are going to upload an image to a webserver. We will convert a BufferedImage to byte array in order to send it to server.

We are going to use java ByteArrayOutputStream class which can be found under java.io package. Its syntax is given below:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);

In order to convert the image to byte array , we are going to use toByteArray() method of ByteArrayOutputStream class. Its syntax is given below:

byte[] bytes = baos.toByteArray();

Apart from the above method, there are other methods available in the ByteArrayOutputStream class which are listed below:

SNMethods with Description
1public void reset()
This method resets the number of valid bytes of the byte array output stream to zero, so all the accumulated output in the stream will be discarded.
2public byte[] toByteArray()
This method creates a newly allocated Byte array. Its size would be the current size of the output stream and the contents of the buffer will be copied into it. Returns the current contents of the output stream as a byte array.
3public String toString()
Converts the buffer content into a string. Translation will be done according to the default character encoding. Returns the String translated from the buffer's content.
4public void write(int w)
Writes the specified array to the output stream.
5public void write(byte []b, int of, int len)
Writes len number of bytes starting from offset off to the stream.
6public void writeTo(OutputStream outSt)
Writes the entire content of this Stream to the specified stream argument.

Example:

Following is the example to demonstrate ByteArrayOutputStream to upload an image to server.

Client Code

import javax.swing.*;  
import java.net.*; 
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Client{
   public static void main(String args[]) throws Exception{
      Socket soc;
      BufferedImage img = null;
      soc=new Socket("localhost",4000);
      System.out.println("Client is running. ");
      try {
         System.out.println("Reading image from disk. ");
         img = ImageIO.read(new File("digital_image_processing.jpg"));
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         
		 ImageIO.write(img, "jpg", baos);
         baos.flush();
         byte[] bytes = baos.toByteArray();
         baos.close();
         System.out.println("Sending image to server. ");
         
		 OutputStream out = soc.getOutputStream(); 
         DataOutputStream dos = new DataOutputStream(out);
         dos.writeInt(bytes.length);
         dos.write(bytes, 0, bytes.length);
         System.out.println("Image sent to server. ");

         dos.close();
         out.close();
      }catch (Exception e) {
         System.out.println("Exception: " + e.getMessage());
         soc.close();
      }
         soc.close();
   }
}

Server Code

import java.net.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*; 
import javax.swing.*; 

class Server {
   public static void main(String  args[]) throws Exception{
      ServerSocket server=null;
      Socket socket;
      server=new ServerSocket(4000);
      System.out.println("Server Waiting for image");

      socket=server.accept();
      System.out.println("Client connected.");
      InputStream in = socket.getInputStream();
      DataInputStream dis = new DataInputStream(in);

      int len = dis.readInt();
      System.out.println("Image Size: " + len/1024 + "KB");
      byte[] data = new byte[len];
      dis.readFully(data);
      dis.close();
	  in.close();

	  InputStream ian = new ByteArrayInputStream(data);
  	  BufferedImage bImage = ImageIO.read(ian);
 
	  JFrame f = new JFrame("Server");
	  ImageIcon icon = new ImageIcon(bImage);
	  JLabel l = new JLabel();
	  l.setIcon(icon);
	  f.add(l);
	  f.pack();
	  f.setVisible(true);
   }
}

Output

Client Side Output

When you run the client code, following output screen would appear on client side.

downloading uploading images

Server Side Output

When you run the server code, following ouptut screen would apppear on server side.

downloading uploading images

After recieving the image , server would display the image like below.

downloading uploading images

Advertisements
Advertisements