Jan 24

Handling images in java using imageIO

Have you ever faced the need of sending an image through a network using a Java program? If yes, you must have probably read the image to a byte array sent it through the network. The problem with this method is it is too long and you have to remake the image file ( using the received byte array) at the destination to take any use of it.

But in this article I’m going to show how to read an image to a Java class called “Image” and use it appropriately. You can use this “Image” class directly in GUI’s, send it through networks, store it, etc. Sol let’s look at the code now. The code consists of two parts. Reading the image to an instance of the “Image” class and writing it back to the hard drive. I have put comments in almost every step. So understanding the code should be easy.

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

public class Main {

 public void copyImage(){

 //path of the image to be read
 String path="picture.jpg";

 //create a file entry in java for that image
 File imageSrc=new File(path);

 if(!imageSrc.exists()){
 System.out.println("Input image does not exist.");
 System.exit(0);
 }

 try {

 /*
 * This part of the code is for reading the image in to
 * an instance of an Image class.
 */

 //Create a stream to read the image
 ImageInputStream iis = ImageIO.createImageInputStream(imageSrc);
 /*
 * ImageIO is a class containing static convenience methods for locating
 *ImageReaders and ImageWriters, and performing simple encoding and decoding.
 */

 //get a collection of Image readers which support jpg
 Iterator<?> imgReaders = ImageIO.getImageReadersByFormatName("jpg");

 //get the first image reader from the collection
 ImageReader reader = (ImageReader) imgReaders.next();

 //set the input for the image reader
 reader.setInput(iis, true);
 /*
 * Setting seekForwardOnly parameter ensures that the image file is
 * read in the ascending order.
 *
 */

 //to ensure that the default read parameters are used when
 //decoding data from the stream
 ImageReadParam param = reader.getDefaultReadParam();

 //read the image
 Image image = reader.read(0, param);

 /*
 *
 * This part of the code is for writing the image object
 * back to the hard disk as an image file.
 */

 //To render the image
 BufferedImage bufferedImage = new BufferedImage(image.getWidth(null),
image.getHeight(null), BufferedImage.TYPE_INT_RGB);

 //using "painter" we can draw in to "bufferedImage"
 Graphics2D painter = bufferedImage.createGraphics();

 //draw the "image" to the "bufferedImage"
 painter.drawImage(image, null, null);

 //the new image file
 File outputImg=new File("output.jpg");

 //write the image to the file
 ImageIO.write(bufferedImage, "jpg", outputImg);

 System.out.println("Image transfer was successful...!");

 } catch (IOException ex) {
 Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
 }
 }

 public static void main(String[] args) {
 // TODO code application logic here

 Main main=new Main();
 main.copyImage();
 }

}

You can download the text file from here.

As you must have understood, I have written the code to read a JPEG image. I tested the same code for BMP, PNG, and TIFF. All those formats worked just fine. The only draw back that I saw was there is a quality loss when using JPEG. To change the image format, change the following code segments (change xxx to the desired foramt).

//path of the image to be read

String path="picture.xxx";

————————————————————————————————————————————————————————–

//get a collection of Image readers which support jpg
 Iterator<?> imgReaders = ImageIO.getImageReadersByFormatName("xxx");

————————————————————————————————————————————————————————–

//the new image file
File outputImg=new File("output.xxx");

————————————————————————————————————————————————————————–

//write the image to the file
ImageIO.write(bufferedImage, "bmp", outputImg);

————————————————————————————————————————————————————————–

If you used a byte array to read the image file, you have to make an image file( on the hard drive) before you use that image again. But using the above method you can directly use it in the Java program. Click here to see an example on that.

As you can see, the possibilities are endless. So experiment and enjoy…..!

Share Button
Jan 20

A basic guide to encryption -2

If you didn’t read the first part of this article you can read it by clicking here.

Ok, let’s continue our discussion on encryption. From this article onwards, I’m going to elaborate on types of encryption. Each of these types has something in common. That is the sender encrypts the set of data ( particularly a file) using a password or a key. When the receiver receives this encrypted file, he is able to use the file using a password/key that he posses. Encryption can be mainly divided in to three categories.

  1. Symmetric-key encryption
  2. Asymmetric-key encryption
  3. Hash functions

Symmetric-key encryption:

The sender and the receiver must have the same key/password. Or if the keys are not identical, they must be related to each other in a predefined specific manner.

Ex:- Sending a password protected zip file to a friend ( you protect the file with a password and tell the password to your friend).

This method is also called as a private-key method and it can be further devided in to two sub-categories.

  1. Stream cypher
  2. Block cypher

Stream cypher:

In a stream cypher, the file is converted bit by bit. For added security the actual message is combined with a keystream. The plaintext gets encrypted adding different cyphertext ( as discussed in the cypher section in the previous article).

Block cypher:

Block ciphers works on a set of bits. A set of bits gets transformed at a time.

Asymmetric-key encryption:

Also called a public key method. This method requires two types of keys,one is called the public-key and the other is called the private-key. The public-keys are distributed publicly. The private-keys only reside with the recipient. The sender who does the encryption should have the public-key which matches the receivers private-key. So when the sender encrypts the file using a public-key, only the receiver with the matching private-key can decrypt it.

Hash functions:

Hash encryption is an one way process and it cannot be reversed. So whats the use of it? Lets take an example from the real world to understand this.

The password for users in a linux operating system was used to be stored in the /etc/passwd file. But the password that was stored in this file was not the real password, but it’s hash value( generated using some unique algorithm-a hash function).When a user needs to login to the system, he enters his user name and password. The password that the user entered is fed to the hash function and the output from the hash function is compared with the hash value in the /etc/passwd file. If the two hash values match, the user was allowed to login to the system . The advantage of this method is the real password is never stored in the computer. So a hacker has no use of the file that contains the password( except if he is using a brute force method).

The aim of these two articles was to give you a basic understanding about cryptography and encryption. I hope you all got something out of it. All your comments are welcome…! .

Share Button
Jan 19

A basic guide to encryption -1

Encryption ? What is it? What’s its relevance to you? Do you think you have never used any kind of an encryption method? If your answer is “no”, definitely you are mistaken!. We use encryption in many events of our day-to-day life. Specially as Internet users encryption helps us a great deal. We are just ignorant about its services. As an example, when you login to your mail account/facebook account you are receiving the protection of encryption methods. We benefit from encryption even in our day-to-day activities like using the ATM. Without the use of encryption technologies, use of ATM machines would have been far more riskier. Through this series of articles, I’m going to give you an introduction to encryption and a basic introduction to some encryption categorizations.

First of all, let’s get familiarized with the terminology.

Cryptography:

This is the study of creating messages in a form of secret code that masks the actual message and displays something completely different. Usually complex mathematical algorithms and computers are used to do this. This encrypted message will mean nothing to a casual observer, but the intended receiver can reconstruct the original message using a certain predefined methodology.

Plaintext:

A data set prior to the encrypting it is called “plaintext”.

Encryption:

Encryption is the implementation of cryptography. Data is converted to an encrypted format using encryption. This encrypted data could be password protected. To decrypt( that means to retrieve the original data) the receiver should have the proper key and/or password.

Ciphertext:

Plaintext data is called “ciphertext” once it is encrypted.

Algorithm:

An algorithm is a precise set of instructions that can be followed to get a reasonable output to a problem. As an example, when sound doesn’t come from your computer speakers, you first check the volume controller of the computer, then you check whether the speaker system has got the power correctly, then you check the volume controller of the speaker system, then you check the connection between the computer and the speaker system. This is more like an “if-then” procedure.

Cipher:

It’s an algorithm that contains precise instructions on how to encrypt and decrypt data. There are two main types of cyphers. The first one rearranges the characters in a file. As an example, the word “ishan” could be rearranged as “snahi”. The second method completely changes the content and replaces it with predeifned characters. As an example, the word “ishan” can be encrypted as “abcde” where i=a, s=b, h=c, a=d, n=e .

Pseudorandomness:

If a process seems to be random, but if it is not random, then thats called pseudorandomness. If a series of things( lets say numbers) seems to be random, but if they are not random, the it’s called a pseudo random series.

Keystream:

It’s a collection of random or pseudorandom characters that is combined with a plaintext message to produce an encrypted message (the ciphertext).

Key:

This is a parameter which determines the functional output of a cryptographic algorithm or cipher. A key is essential to get a result that is useful.

Brute force attack:

When a person tries to crack the encryption algorithm by using an intensive trial-and-error key/password reproduction procedure, it is called a brute force attack.

I think this is enough for a single post. Hope to you see you soon with the next part of this article…!

Share Button