0

I have a java class generating an image from a random String, the java code works fine when I run individually and the image is being save in the local directory.

Now I created a simple JSP form for registration, how do I display out the image in the html <img> in JSP. Below is my code:

index.jsp

<%@page import="javax.imageio.ImageIO"%>
<%@page import="java.awt.image.BufferedImage"%>
<%@page import="convert.references"%>
<%@page import="java.io.*, java.util.*"%>
<html>
<head>
<title>Echoing HTML Request Parameters</title>
</head>
<body>  
<h3>Registering user...</h3>
<form method="get">
    Please enter your Username:
    <input type="text" name="username"/><br>
    Please enter your Email:
    <input type="text" name="email"><br>
    Please enter your Security Question:
    <input type="text" name="qn"><br>
    Please enter your Security Answer:
    <input type="text" name="ans"><br>
    Please enter your Recovery Password:
    <input type="password" name="pass"><br>    
    <input type="submit" value="Enter">
</form> 
<%
    String username = request.getParameter("username");
    String email = request.getParameter("email");
    String qn = request.getParameter("qn");
    String ans = request.getParameter("ans");
    String pass = request.getParameter("pass");

    if (username != null) {          
        references test = new references();
        BufferedImage image = test.stringToImage(); 
        File outputfile = new File("saved.png");
        ImageIO.write(image, "png", outputfile);
%>  
    <h3>Your details:</h3>
    <ul>
        <li><%= username %></li>
        <li><%= email %></li>
        <li><%= qn %></li>
        <li><%= ans %></li>
        <li><%= pass %></li>
        <li><img src="<%= outputfile%>" alt="Image not found" /></li>
    </ul>
    <a href="<%= request.getRequestURI() %>">BACK</a>
<%
}
%>
</body>
</html>

references.java (working fine individually, able to generate out)

package convert;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.util.Random;
import java.util.Scanner;

public class references {

    private final int stringLength = 10;

    public BufferedImage stringToImage(){
            //reference from: http://stackoverflow.com/questions/18800717/convert-text-content-to-image
            Scanner reader = new Scanner(System.in);            
            String imageText = "";
            for(int count = 0; count < stringLength; count++){                      //consisting of 8 value
                Random rand = new Random();                                         //randomly selected
                int randomNumber = rand.nextInt(10);                                //of 1-9
                imageText += randomNumber;                                          //one number at a time for 8 times
            }
            BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = img.createGraphics();
            Font font = new Font("Arial", Font.PLAIN, 48);
            g2d.setFont(font);
            FontMetrics fm = g2d.getFontMetrics();
            int width = fm.stringWidth(imageText);
            int height = fm.getHeight();
            g2d.dispose();

            img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            g2d = img.createGraphics();
            g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
            g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
            g2d.setFont(font);
            fm = g2d.getFontMetrics();
            g2d.setColor(Color.BLACK);
            g2d.drawString(imageText, 0, fm.getAscent());
            g2d.dispose();
            /*try{
                File outputfile = new File("saved.png");
                ImageIO.write(img, "png", outputfile);
            } catch (IOException e) {}*/
            return img;
        }
}

Any alternate ways to generate out the image and display on jsp?

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Tommy Yap
  • 85
  • 1
  • 9
  • Your file creation code works. But, you created the saved.png file where the browser can't get it. You used a relative path in the File constructor. According to the API, the file was created in the "directory in which the Java virtual machine was invoked". In Tomcat, that is it's bin folder. – rickz Aug 06 '16 at 17:36

1 Answers1

-1

You can use <img src="saved.png"> in your jsp. As long as saved.png is located in your web applicaton context root.

An alternative way would be to create a servlet that will handle on the fly image generation (without the need of saving to the hard drive). And then in jsp you would reference the servlet as the src of the image.

PKey
  • 3,715
  • 1
  • 14
  • 39
  • Carefully read this: http://stackoverflow.com/q/31255366 – BalusC Aug 06 '16 at 10:53
  • @BalusC If I understood you correctly - you are opposed to saving files in context root. But as you can see I suggested to use servlet instead... however If the author keeps the original design (unorthodox or not) - how else would he show that image of his. – PKey Aug 06 '16 at 11:04