0

在普通的 Servlet 中,我可以使用以下代码生成图像:

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException 
{
    int width = 200, height = 200;
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();

    drawInside(g); // draw on g

    // return
    response.setContentType("image/jpeg");
    OutputStream out = response.getOutputStream();
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    encoder.encode(image);
    out.close();
}

但是 Android 不支持 BufferedImage 和 Graphics,所以我需要使用这样的东西:

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException 
{
    int width = 200, height = 200;
    Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas g = new Canvas(image);

    drawInside(g); // draw on g

    // ...
}

但 Android 也不支持 JPEGImageEncoder。如何将图像写入 ServletResponse.getOutputStream()?

4

1 回答 1

1

这里是答案:

    response.setContentType("image/jpeg");
    OutputStream out = response.getOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, out);
于 2013-05-28T09:19:52.577 回答