SAVING IMAGES IN A DATABASE USING EJBS

It is sometimes troublesome to save and retrieve images in  a database using java. Below are methods that are useful in saving and retrieving images from a database

To save an image in a database the datatype of the column should be “blob”. One thing to note is that in the EJBs the blob datatype is change to an array of bytes (“byte[]”)

A function to change an image file into its bytes

public Function byte[] setImagebytes(File imageFile) {

byte[] imagebytes = null;

try {

FileInputStream fis = new FileInputStream(imageFile);

imagebytes = new byte[(int) imageFile.length()];

fis.read(imagebytes);

} catch (FileNotFoundException ex) {

ex.printStackTrace();

} catch (IOException ex) {

ex.printStackTrace();

}

Return imagebytes;

}

A method to browse for an image file from its location and show it in a label

private void btBrowseActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

// a method to browse for a picture and pass the image file to the setImagebytes method

fc.setFileFilter(new FileNameExtensionFilter("Images", "jpg", "gif", "bmp"));

if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {

fc.setCurrentDirectory(fc.getCurrentDirectory());

ImageIcon icon = new ImageIcon(fc.getSelectedFile().getAbsolutePath());

icon = new ImageIcon(icon.getImage().getScaledInstance(150, 150, Image.SCALE_DEFAULT));

this.lbPicture.setIcon(icon);

//passing the image file to the setImagebytes to create the image bytes

this.setImagebytes(fc.getSelectedFile());

//icon.getImage()

repaint();

}

}

A method to convert the bytes array (byte[]) into a pictures to display in a label

Private void getRealImage(byte[] imagebytes){

if (imagebytes != null) {

ImageIcon icon = new ImageIcon(imagebytes);

icon = new ImageIcon(icon.getImage().getScaledInstance(150, 150, Image.SCALE_DEFAULT));

this.lbPicture.setIcon(icon);

} else {

ImageIcon icon = new ImageIcon();

//showing the image in a label

this.lbPicture.setIcon(icon);

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s