Wednesday, January 6, 2016

Simple Captcha by PrimeFaces graphicImage

Basically the concept is to generate random text and display it with image, which is <p:graphicImage />.

1. Write a method to generate the StreamedContent.
public StreamedContent getCaptcha() {
    StreamedContent 2dText = null;
    try {
        BufferedImage bufferedImg = new BufferedImage(
                100, 25, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bufferedImg.createGraphics();
        
        String captchaText = generateRandomString();            
        
        g2.drawString(captchaText, 0, 10);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(bufferedImg, "png", os);
        2dText = new DefaultStreamedContent(
                new ByteArrayInputStream(os.toByteArray()), "image/png"); 
    } 
    catch (Exception e) {
        e.printStackTrace();
    }
    return 2dText;
}



2. the generateRandomString() method is your own logic to generate the random captcha text.
public String generateRandomString() {
    // some logic to generate random String

    return randomString; 
}


3. Display the StreamedContent with <p:graphicImage />
<p:graphicImage value="#{myBean.captcha}" />



Done!!

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...