I want the JSP program where user wants to upload an image into MySQL DB while uploading I want to convert image Dimensions as per my specified size like 300x300px. Plz help me.
my JSP code
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<form method="post" action="imageAPI" enctype="multipart/form-data">
<input type="file" name="pic"/><br/>
<input type="submit" value="send"/>
</form>
</body>
</html>
my servlet code
@WebServlet(urlPatterns = {"/imageAPI"})
@MultipartConfig(maxFileSize = 16177215)
public class imageAPI extends HttpServlet {
private String dbURL = "jdbc:mysql://localhost/OBS";
private String dbUSER = "root";
private String dbPASS = "1234";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Connection con = null;
InputStream is = null;
Image image = null;
BufferedImage thumb = null;
Part filePart = req.getPart("pic");
int thumbWidth = 600;
int thumbHeight = 600;
if(filePart != null){
is = filePart.getInputStream();
image = ImageIO.read(is);
thumb = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = thumb.createGraphics();
graphics2D.setBackground(Color.WHITE);
graphics2D.setPaint(Color.WHITE);
graphics2D.fillRect(0, 0, thumbWidth, thumbHeight);
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
ImageIO.write(thumb, "JPG", resp.getOutputStream());
}
try{
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
con = DriverManager.getConnection(dbURL, dbUSER, dbPASS);
String sql = "insert into imageapi (image) values(?)";
PreparedStatement ps = con.prepareStatement(sql);
if(is!= null){
ps.setBlob(1,(Blob) ImageIO.read((ImageInputStream) thumb));
}
con.close();
ps.close();
}catch(SQLException ex){
ex.printStackTrace();
}
}
}