如何将图像从REST服务方法返回到浏览器

时间:2018-10-06 18:51:47

标签: java image rest glassfish javax.imageio

目标-我正在创建自己的验证码,其中有一个客户端,我将从该客户端在Java后端进行class A { public: constexpr A () { } }; template <int N, A const (& obj)[N]> struct W { }; constexpr A b[5]; int main () { W<5, b> w; } 调用。在后端,我有一个程序,该程序将生成一个随机字符串,然后将其转换为图像,然后将其返回到客户端以进行渲染,以便用户可以输入与图像中相同的字符,并且验证码可以是已验证。

方法-我有一个REST调用,该调用返回REST,在此过程中,我绑定了CaptchaImage以便可以将其呈现给浏览器。该方法有点类似于How to return a PNG image from Jersey REST service method to the browser

代码: ICaptchaServlet.java-接口

javax.ws.rs.core.Response

CaptchaServlet.java

import java.io.IOException;
import java.security.GeneralSecurityException;

import javax.servlet.http.*;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;

public interface ICaptchaServlet{

    public Response processRequest(@Context HttpServletRequest req) throws GeneralSecurityException, IOException;

    @GET
    @Path("/getChallenge")
    public Response doGet(@Context HttpServletRequest req) throws GeneralSecurityException;
}

问题:我已放入系统日志语句,以帮助更好地跟踪问题。当我执行此操作时,Rest Service调用不会返回SUCCESS,而是转到ERROR回调函数。图像未渲染。 我已经尝试了以下两种方法:

import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

//Internal Rest Service annotation which it picks up fine
@Named("CaptchaServlet")
@Path("/reCaptchaImg")
@Produces("image/png")
public class CaptchaServlet implements ICaptchaServlet{

    @Override
    public Response processRequest(HttpServletRequest request) throws GeneralSecurityException, IOException {
        System.out.println("shaan Inside processRequest");
        int width = 150;
        int height = 50;

        //Random string generation happens
        Random r = new Random();
        int length = 6;
        System.out.println("shaan Creating string parameter");
        StringBuffer captchaStringBuffer = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int baseCharNumber = ((r.nextInt((500-1)+1)+1) % 62);
            int charNumber = 0;
            if (baseCharNumber < 26) {
              charNumber = 65 + baseCharNumber;
            }
            else if (baseCharNumber < 52){
              charNumber = 97 + (baseCharNumber - 26);
            }
            else {
              charNumber = 48 + (baseCharNumber - 52);
            }
            captchaStringBuffer.append((char)charNumber);
        }
        String captchaString = captchaStringBuffer.toString();
        System.out.println("The random string generated is : "+captchaString);

        char[] s3 = captchaString.toCharArray();
        System.out.println("shaan1");

        //Converting Captcha String to Image
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bufferedImage.createGraphics();
        System.out.println("shaan2");
        Font font = new Font("Georgia", Font.BOLD, 18);
        g2d.setFont(font);
        System.out.println("shaan3");
        RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        System.out.println("shaan4");
        rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHints(rh);
        System.out.println("shaan5");
        GradientPaint gp = new GradientPaint(0, 0, Color.red, 0, height / 2, Color.black, true);
        g2d.setPaint(gp);
        g2d.fillRect(0, 0, width, height);
        g2d.setColor(new Color(255, 153, 0));
        System.out.println("shaan6");
        String captcha = String.copyValueOf(s3);
        System.out.println("shaan7");
        int x = 0;
        int y = 0;
        for (int i = 0; i < s3.length; i++) {
            x += 10 + (Math.abs(r.nextInt()) % 15);
            y = 20 + Math.abs(r.nextInt()) % 20;
            g2d.drawChars(s3, i, 1, x, y);
        }
        g2d.dispose();
        System.out.println("shaan8");
        System.out.println("shaan9");

        //Sending Image in output
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", baos);
        byte[] imageData = baos.toByteArray();
        System.out.println("shaan10" + captcha);
        request.getSession().setAttribute("captcha", captcha);
        System.out.println("shaan11");
        baos.flush();
        baos.close();
        System.out.println("shaan12");
        System.out.println("The imageData is :"+imageData);
        // uncomment line below to send non-streamed
        //return Response.ok(imageData).build();

        // uncomment line below to send streamed
         return Response.ok(new ByteArrayInputStream(imageData)).build();
    }

    @Override
    public Response doGet(HttpServletRequest request) throws GeneralSecurityException {
        System.out.println("shaan inside doGet");
        Response response = null;
        try {
            response =  processRequest(request);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return response;
    }

}

日志:

// uncomment line below to send non-streamed
//return Response.ok(imageData).build();

// uncomment line below to send streamed
// return Response.ok(new ByteArrayInputStream(imageData)).build();

0 个答案:

没有答案