Friday, August 20, 2010

Download images from Database in JSP

Step:1 To create a "imageupload" table in Database

CREATE TABLE `imageupload` (
`id` bigint(20) NOT NULL auto_increment,
`imagefile` blob NOT NULL,
PRIMARY KEY (`id`)
)

Step:2 To create a web page "image.jsp"
<%@ page import="java.sql.*,java.io.*,java.util.*" %>
<%

String connectionURL = "jdbc:mysql://localhost:3306/userdetails";
if(request.getParameter("imgid")!=null && request.getParameter("imgid")!="")
{
int id = Integer.parseInt(request.getParameter("imgid"));

String filename = "image"+id+".jpg";
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection(connectionURL,"root","root");
Statement st1=con.createStatement();
String strQuery = "select imagefile from imageupload where id="+id;

ResultSet rs1 = st1.executeQuery(strQuery);

String imgLen="";
if(rs1.next()){
imgLen = rs1.getString(1);
}
rs1 = st1.executeQuery(strQuery);
if(rs1.next()){
int len = imgLen.length();
byte [] rb = new byte[len];
InputStream readImg = rs1.getBinaryStream(1);
int index=readImg.read(rb, 0, len);
st1.close();
response.reset();
response.setContentType("image/jpg");
response.setHeader("Content-disposition","attachment; filename=" +filename);
response.getOutputStream().write(rb,0,len);
response.getOutputStream().flush();
}
}
catch (Exception e){
e.printStackTrace();
}
}
%>

Step:3 To create a "imageDownload.jsp"

<%@ page import="java.sql.*,java.io.*,java.util.*" %>


Download Images






"center" border=0 width="200px">




<%

String connectionURL = "jdbc:mysql://localhost:3306/userdetails";
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection(connectionURL,"root","root");
Statement stmt=con.createStatement();
String strQuery = "select id from imageupload";
ResultSet rs = stmt.executeQuery(strQuery);
int sno=0;
while(rs.next())
{
sno++;
%>
"background-color:#efefef;">



<%
}
rs.close();
con.close();
stmt.close();
}
catch(Exception e)
{
e.getMessage();
}
%>
2 align="center">Download Images
2>
<%=sno%> "center">
"image.jsp?imgid=<%=rs.getInt(1)%>">
"image.jsp?imgid=<%=rs.getInt(1)%>" width="50" height="50">



How to resize and compress images

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/


import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import javax.activation.MimetypesFileTypeMap;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;

/**
*
* @author monirul
*/
public class ImageResizer {


@SuppressWarnings("OverridableMethodCallInConstructor")
ImageResizer()
{

try
{
// this is just for my own local testing
// simulate byte[] input from database
FileWriter writer = new FileWriter(new File("D:/output2/error.txt"));
File source = new File("D:/input/");
File[] dir = null;
if(source.isDirectory())
{
// Get a list of all of the Excel spreadsheet files (workbooks) in
// the source folder/directory
dir = source.listFiles();
}
else
{
// Assume that it must be a file handle - although there are other
// options the code should perhaps check - and store the reference
// into the filesList variable.
dir = new File[]{source};
}
int i=0;
for(File dir1: dir)
{
i++;
System.out.println("Folder :"+i+" "+dir1);
File[] filesList = null;
//System.out.println(dir1.toString());
if(dir1.isDirectory())
{

try
{
File outputPath = new File(dir1.toString().replaceAll("input","output1"));
outputPath.mkdir();
//System.out.println("Monirul");
}
catch(Exception e)
{
//System.out.println(e);
}
try
{
File outputPath = new File(dir1.toString().replaceAll("input","output2"));
outputPath.mkdir();
//System.out.println("Monirul");
}
catch(Exception e)
{
//System.out.println(e);
}
// Get a list of all of the Excel spreadsheet files (workbooks) in
// the source folder/directory
filesList = dir1.listFiles();
getFiles1(filesList,writer);
}
else
{
// Assume that it must be a file handle - although there are other
// options the code should perhaps check - and store the reference
// into the filesList variable.
filesList = new File[]{dir1};
getFiles1(filesList,writer);

}


}
writer.close();
}
catch(Exception e)
{
// System.out.println(e);
}
}


public void getFiles1(File[] filesList,FileWriter writer)
{
try
{
for(File imageFile:filesList)
{
//BufferedImage image = ImageIO.read(new File("D:/input/image1.jpg"));
BufferedImage image1 = ImageIO.read(imageFile);
BufferedImage image2 = ImageIO.read(imageFile);
int imageSourceWidth = image1.getWidth();
int imageSourceHeight = image1.getHeight();
int newImageHight1=0;
int newImageWidth1=0;
int newImageHight2=0;
int newImageWidth2=0;
//System.out.println(imageSourceWidth);
//System.out.println(imageSourceHeight);
if(imageSourceWidth>imageSourceHeight)
{
newImageHight1=50;
newImageWidth1=100;
newImageHight2=300;
newImageWidth2=450;
}
else if(imageSourceWidth {
newImageHight1=100;
newImageWidth1=50;
newImageHight2=450;
newImageWidth2=300;
}
else if(imageSourceWidth==imageSourceHeight)
{
newImageHight1=106;
newImageWidth1=106;
newImageHight2=450;
newImageWidth2=450;
}
{

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(image1, "PNG", byteArrayOutputStream);
byte[] sourceBytes = byteArrayOutputStream.toByteArray();
byte[] scaledBytes = resizeImage1(sourceBytes,imageSourceWidth,imageSourceHeight,newImageWidth1,newImageHight1);
// write out again to check result
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(scaledBytes);
image1 = ImageIO.read(byteArrayInputStream);
String path = imageFile.toString().replaceAll("input","output1");
//System.out.println(path);
ImageIO.write(image1, "PNG", new File(path));
}

{


// File file = new File();
String fType = new MimetypesFileTypeMap().getContentType(imageFile).replaceAll("image/", "");
System.out.println("Extension of the file is : "+fType);
String path = imageFile.toString().replaceAll("input","output2");
try
{
compressAndSave(image2,0.5f,fType,newImageHight2,newImageWidth2,new File(path));
}
catch(Exception e)
{

writer.append(path);
writer.append("\n");
System.out.println(e);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(image2, "PNG", byteArrayOutputStream);
byte[] sourceBytes = byteArrayOutputStream.toByteArray();
byte[] scaledBytes = resizeImage1(sourceBytes,imageSourceWidth,imageSourceHeight,newImageWidth2,newImageHight2);
// write out again to check result
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(scaledBytes);
image2 = ImageIO.read(byteArrayInputStream);
String path1 = imageFile.toString().replaceAll("input","output2");
//System.out.println(path);
ImageIO.write(image2, "PNG", new File(path1));
}

// ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// ImageIO.write(image2, "PNG", byteArrayOutputStream);
// byte[] sourceBytes = byteArrayOutputStream.toByteArray();
// byte[] scaledBytes = resizeImage2(image2,sourceBytes,imageSourceWidth,imageSourceHeight,newImageWidth2,newImageHight2);
// // write out again to check result
// ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(scaledBytes);
// image2 = ImageIO.read(byteArrayInputStream);

}

}
}catch(Exception e)
{
// System.out.println(e);
}
}

public static void main(String []args)
{
new ImageResizer();
}

public static void compressAndSave(BufferedImage image, float quality,String fileType,int newHeight,int newWidth,File outputFile) throws IOException
{


// Get a ImageWriter for jpeg format.
Iterator writers = ImageIO.getImageWritersBySuffix(fileType);
if (!writers.hasNext()) throw new IllegalStateException("No writers found");
ImageWriter writer = (ImageWriter) writers.next();
// Create the ImageWriteParam to compress the image.
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
// The output will be a ByteArrayOutputStream (in memory)
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
ImageOutputStream ios = ImageIO.createImageOutputStream(bos);
writer.setOutput(ios);
writer.write(null, new IIOImage(image, null, null), param);
ios.flush(); // otherwise the buffer size will be zero!
// From the ByteArrayOutputStream create a RenderedImage.
ByteArrayInputStream in = new ByteArrayInputStream(bos.toByteArray());
BufferedImage out = ImageIO.read(in);
int type=out.getType();
int size = bos.toByteArray().length;
BufferedImage resizedImage = new BufferedImage(newWidth,newHeight, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(image, 0, 0,newWidth,newHeight, null);
g.dispose();
//Uncomment code below to save the compressed files.
ImageIO.write(resizedImage,fileType,outputFile);
//FileImageOutputStream output = new FileImageOutputStream(outputFile);
//writer.setOutput(output); writer.write(null, new IIOImage(resizedImage, null,null), param);
}

private byte[] resizeImage2(BufferedImage image2,byte[] sourceBytes,int imageSourceWidth,int imageSourceHeight, int newWidth, int newHeight) throws Exception
{
byte[] scaledBytes;
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(sourceBytes);
// Why not just use ImageIO.read(inputStream)? - Because there would be
// no way to know the original image format (I am assuming here that
// you need to write back the image in the same format as the original)
ImageInputStream imageInputStream = ImageIO.createImageInputStream(byteArrayInputStream);
// assuming there is at least one ImageReader able to read the image
ImageReader imageReader = ImageIO.getImageReaders(imageInputStream).next();
// save image format name so we can write it back in the same format
String formatName = imageReader.getFormatName();

imageReader.setInput(imageInputStream);
BufferedImage sourceImage = imageReader.read(0);

//int imageSourceWidth = sourceImage.getWidth();
//int imageSourceHeight = sourceImage.getHeight();
//if (imageSourceWidth > newWidth) {
// be careful with integer divisions ( 500 / 1000 = 0!)
//double scaleFactor = (double) newWidth / (double) imageSourceWidth;
//int newHeight = (int) Math.round(imageSourceHeight * scaleFactor);
//System.out.println("newWidth=" + newWidth + ", newHeight=" + newHeight + ", formatName=" + formatName);
// getScaledInstance provides the best downscaling quality but is
// orders of magnitude slower than the alternatives
// since you're saying performance is not issue, I leave it as is
Image scaledImage = sourceImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
// Unfortunately we need a RenderedImage to use ImageIO.write.
// So the next lines convert whatever type of Image was returned
// by getScaledImage into a BufferedImage.
// Using TYPE_INT_ARGB so potential alpha channels are preserved
BufferedImage scaledBufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);

Graphics2D g2 = scaledBufferedImage.createGraphics();
g2.drawImage(scaledImage, 0, 0, null);
g2.dispose();
// Now use ImageIO.write to encode the image back into a byte[],
// using the same image format
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(32768);
ImageIO.write(scaledBufferedImage, formatName, byteArrayOutputStream);
scaledBytes = byteArrayOutputStream.toByteArray();
//} else {
// if not scaling happened, just return the original byte[]
//scaledBytes = sourceBytes;
//}

return scaledBytes;
}

private byte[] resizeImage1(byte[] sourceBytes,int imageSourceWidth,int imageSourceHeight, int newWidth, int newHeight) throws Exception
{
byte[] scaledBytes;
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(sourceBytes);
// Why not just use ImageIO.read(inputStream)? - Because there would be
// no way to know the original image format (I am assuming here that
// you need to write back the image in the same format as the original)
ImageInputStream imageInputStream = ImageIO.createImageInputStream(byteArrayInputStream);
// assuming there is at least one ImageReader able to read the image
ImageReader imageReader = ImageIO.getImageReaders(imageInputStream).next();
// save image format name so we can write it back in the same format
String formatName = imageReader.getFormatName();
imageReader.setInput(imageInputStream);
BufferedImage sourceImage = imageReader.read(0);

//int imageSourceWidth = sourceImage.getWidth();
//int imageSourceHeight = sourceImage.getHeight();
//if (imageSourceWidth > newWidth) {
// be careful with integer divisions ( 500 / 1000 = 0!)
//double scaleFactor = (double) newWidth / (double) imageSourceWidth;
//int newHeight = (int) Math.round(imageSourceHeight * scaleFactor);
//System.out.println("newWidth=" + newWidth + ", newHeight=" + newHeight + ", formatName=" + formatName);
// getScaledInstance provides the best downscaling quality but is
// orders of magnitude slower than the alternatives
// since you're saying performance is not issue, I leave it as is
Image scaledImage = sourceImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
// Unfortunately we need a RenderedImage to use ImageIO.write.
// So the next lines convert whatever type of Image was returned
// by getScaledImage into a BufferedImage.
// Using TYPE_INT_ARGB so potential alpha channels are preserved
BufferedImage scaledBufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);

Graphics2D g2 = scaledBufferedImage.createGraphics();
g2.drawImage(scaledImage, 0, 0, null);
g2.dispose();
// Now use ImageIO.write to encode the image back into a byte[],
// using the same image format
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(32768);
ImageIO.write(scaledBufferedImage, formatName, byteArrayOutputStream);
scaledBytes = byteArrayOutputStream.toByteArray();
//} else {
// if not scaling happened, just return the original byte[]
//scaledBytes = sourceBytes;
//}

return scaledBytes;
}


}

Shallow and deep cloning in java

The steps for making a deep copy using serialization are:

Ensure that all classes in the object's graph are serializable

1.Create input and output streams.

2.Use the input and output streams to create object input and object output streams.

3.Pass the object that you want to copy to the object output stream.

4.Read the new object from the object input stream and cast it back to the class of the object you sent.


The class for serialization

import java.io.*;

import java.util.*;

import java.awt.*;

public class ObjectCloner

{

// so that nobody can accidentally create an ObjectCloner object

private ObjectCloner(){}

// returns a deep copy of an object

static public Object deepCopy(Object oldObj) throws Exception

{

ObjectOutputStream oos = null;

ObjectInputStream ois = null;

try

{

ByteArrayOutputStream bos =

new ByteArrayOutputStream(); // A

oos = new ObjectOutputStream(bos); // B

// serialize and pass the object

oos.writeObject(oldObj); // C

oos.flush(); // D

ByteArrayInputStream bin =

new ByteArrayInputStream(bos.toByteArray()); // E

ois = new ObjectInputStream(bin); // F

// return the new object

return ois.readObject(); // G

}

catch(Exception e)

{

System.out.println("Exception in ObjectCloner = " + e);

throw(e);

}

finally

{

oos.close();

ois.close();

}

}

}




The main class


import java.util.*;

import java.awt.*;

public class Driver1

{

static public void main(String[] args)

{

try

{

// get the method from the command line

String meth;

if((args.length == 1) &&

((args[0].equals("deep")) || (args[0].equals("shallow"))))

{

meth = args[0];

}

else

{

System.out.println("Usage: java Driver1 [deep, shallow]");

return;

}

// create original object

Vector v1 = new Vector();

Point p1 = new Point(1,1);

v1.addElement(p1);

// see what it is

System.out.println("Original = " + v1);

Vector vNew = null;

if(meth.equals("deep"))

{

// deep copy

vNew = (Vector)(ObjectCloner.deepCopy(v1)); // A

}

else if(meth.equals("shallow"))

{

// shallow copy

vNew = (Vector)v1.clone(); // B

}

// verify it is the same

System.out.println("New = " + vNew);

// change the original object's contents

p1.x = 2;

p1.y = 2;

// see what is in each one now

System.out.println("Original = " + v1);

System.out.println("New = " + vNew);

}

catch(Exception e)

{

System.out.println("Exception in main = " + e);

}

}

}