Java get image extension/type using BufferedImage from URL

后端 未结 4 1219
死守一世寂寞
死守一世寂寞 2020-12-05 13:40

I am familiar with working with images. I retrieve/read an image from a URL, where the URL does not have a file extension. Then I wish to write/save the image to the local s

4条回答
  •  时光取名叫无心
    2020-12-05 13:59

    If you get the image from a URL, that means you can access the image through an InputStream. From that you can use ImageIO to get the image type (format) and with the following code, create a BufferedImage at the same time.

    public static BufferedImageWrapper getImageAndTypeFromInputStream(InputStream is) {
    
        String format = null;
        BufferedImage bufferedimage = null;
        try (ImageInputStream iis = ImageIO.createImageInputStream(is);) {
    
          Iterator readers = ImageIO.getImageReaders(iis);
    
          if (readers.hasNext()) {
    
            ImageReader reader = readers.next();
            format = reader.getFormatName();
            reader.setInput(iis);
            bufferedimage = reader.read(0);
          }
        } catch (IOException e) {
          logger.error("ERROR DETERMINING IMAGE TYPE!!!", e);
        }
    
        return new BufferedImageWrapper(format, bufferedimage);
      }
    
      public static class BufferedImageWrapper {
    
        private final String imageType;
        private final BufferedImage bufferedimage;
    
        /**
         * Constructor
         *
         * @param imageType
         * @param bufferedimage
         */
        public BufferedImageWrapper(String imageType, BufferedImage bufferedimage) {
          this.imageType = imageType;
          this.bufferedimage = bufferedimage;
        }
    
        public String getImageType() {
    
          return imageType;
        }
    
        public BufferedImage getBufferedimage() {
    
          return bufferedimage;
        }
    
      }
    

提交回复
热议问题