0

I am developing a web app, which has the functionality of displaying images obtained from a server. I learned that I can do it by returning byte array in response.

It seems that I am able to do it through:

@RequestMapping(value = "url/img", method = RequestMethod.POST)
@ResponseBody
public MyDto proceedDocumentFromUrl(@RequestParam final String url) throws IOException {
    return somethingDoer.do(toByteArray(new URL(url).openStream());
}

somethingDoer.do returns Dto object which contains byte[] In field named image. For test purposes I would like to determine the image extension (it is always .jpg).

How can I do that? I was looking in Wiki and W3 documents for some clue(I suppose it is about first few bytes) but was unable to find a solution.

reto
  • 9,995
  • 5
  • 53
  • 52
don_pablito
  • 382
  • 1
  • 9

1 Answers1

0

Please check this getFormatName(file) method and check Class ImageReader

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

public class Main {
  public static void main(String[] argv) throws Exception {
    File file = new File("image.gif");
    System.out.println(getFormatName(file));

    InputStream is = new FileInputStream(file);
    is.close();
    System.out.println(getFormatName(is));
  }
  private static String getFormatName(Object o) {
    try {
      ImageInputStream iis = ImageIO.createImageInputStream(o);
      Iterator iter = ImageIO.getImageReaders(iis);
      if (!iter.hasNext()) {
        return null;
      }
      ImageReader reader = (ImageReader) iter.next();
      iis.close();

      return reader.getFormatName();
    } catch (IOException e) {
    }
    return null;
  }
}

Please check https://github.com/arimus/jmimemagic to get extension from byte[]

byte[] data = someData
MagicMatch match = Magic.getMagicMatch(data);
System.out.println( match.getMimeType());
Subodh Joshi
  • 12,717
  • 29
  • 108
  • 202
  • Thank you for your answer, however i want to determine image extension when its converted to byte[] and then to string (in 'HttpResponse'), not when i read it from file. Regards. – don_pablito Aug 14 '15 at 07:20
  • Please check this http://stackoverflow.com/questions/10040330/how-to-extract-file-extension-from-byte-array – Subodh Joshi Aug 14 '15 at 07:23