0

I need to download file from a given url, but the thing is I can get files with no extension. In order to figure out what the extension is I wrote the following service:

    public String getExtension(String imageURL){
        InputStream stream = new URL(imageURL).openStream();
        ImageInputStream iis = ImageIO.createImageInputStream(stream);
        Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
        ImageReader reader = imageReaders.next();
        String retVal      = reader.getFormatName();
        closeInputStreamAndDisposeReader(reader);
        return retVal;
    }

Later on I need to download that image so I wrote:

    BufferedImage image = ImageIO.read(imageURL);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ImageIO.write( image, extension, byteArrayOutputStream );
    byteArrayOutputStream.flush();
    byte[] imageInBytes = byteArrayOutputStream.toByteArray();
    byteArrayOutputStream.close();

The problem is that I'm dowloading the file twice - and I would like to use the cache in order to prevent that. Now I read about ImageIO.setUseCache(false); but it doesn't seems to work (perhaps I'm doing something wrong here).

Edit: I've noticed that I create the input stream using new URL(imageURL).openStream() - this is the first download that I'm doing, I think that I should have used one of the ImageIO methods to get that and then the ImageIO.setUseCache(false); would work.

Am I right?

How can I do that - I tried to use the ImageIO.createImageInputStream(imageURL); but I got an exception:

java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.createImageInputStream(Unknown Source)

So, how can I do that?

Thanks.

Noam
  • 3,049
  • 10
  • 34
  • 52
  • 1
    Do you need help to write an `InputStream` to a temporary file and reading from it later on? Or making `image` an instance field? – Raffaele Aug 06 '12 at 08:56
  • I need to get that inputStream from a given url and read from it later on – Noam Aug 06 '12 at 09:19
  • Try `ImageIO.createImageInputStream(imageURL.openStream())` instead. I think once you've done this, the cache "should" work for you, as from what I've read it works with `ImageInput/OutputStream` – MadProgrammer Aug 06 '12 at 09:29

1 Answers1

1

What I've done in the past is use a Map backed Cache, which basically takes the URL as the key a File reference as the value.

Basically what I would do is request an Image from the cache via an URL. If the image had already been downloaded (and it meets a few other requirements), it returns the Image that exists on the file system, otherwise, it downloads it and places into the cache.

You could extend the idea but providing things like isCached(URL) and getFile(URL) or even getInputStream(URL) or getReader(URL) or what ever it is you need

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366