0

How to download an image from a server and then write it as a response in my servlet. What is the best way to do it keeping good performance?

Here's my code:

JSONObject imageJson;
... //getting my JSON
String imgUrl = imageJson.get("img");
Oleg
  • 2,984
  • 8
  • 43
  • 71

3 Answers3

2

if you don't need to hide your image source and if server is accessible from the client as well, I'd just point your response to remote server (as you already have the url) => you don't need to do a download to your server first, but possibly client could access it directly => you don't waste your resources.

However if you still need to download it to your server first, following post might help: Writing image to servlet response with best performance

Community
  • 1
  • 1
Peter Butkovic
  • 11,143
  • 10
  • 57
  • 81
1

It's important to avoid intermediate buffering of image in servlet. Instead just stream whatever was received to the servlet response:

InputStream is = new URL(imgUrl).openStream();
OutputStream os = servletResponse.getOutputStream();

IOUtils.copy(is, os);
is.close();

I'm using IOUtils from Apache Commons (not necessary, but useful).

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
0

The complete solution : download a map and save to file.

    String imgUrl = "http://maps.googleapis.com/maps/api/staticmap?center=-15.800513,-47.91378&zoom=11&size=200x200&sensor=false";
    InputStream is = new URL(imgUrl).openStream();
    File archivo = new File("c://temp//mapa.png");
    archivo.setWritable(true);
    OutputStream output = new FileOutputStream(archivo);
    IOUtils.copy(is, output);
    IOUtils.closeQuietly(output);
    is.close();
Amith
  • 6,818
  • 6
  • 34
  • 45