0

I'm using below code but this code generate and save image in my localbut I need to convert and process that image into WebP byte Array without saving the image in my local. I'm using 3rd party Library to compress the image.

Library that I used :

<dependency> 
    <groupId>org.sejda.imageio</groupId> 
    <artifactId>webp-imageio</artifactId> 
    <version>0.1.6</version> 
</dependency>



public static void main(String[] args) {    

String s = "https://upload.wikimedia.org/wikipedia/commons/f/f9/Phoenicopterus_ruber_in_S%C3%A3o_Paulo_Zoo.jpg";
    
    try {
        URL url = new URL(s.replaceAll(" ", "%20"));
        InputStream is = null;
        try {
            is = url.openStream();
        } catch (IOException e) {
            return;
        }
         BufferedImage image = ImageIO.read(is);
         
          ImageWriter writer =           ImageIO.getImageWritersByMIMEType("image/webp").next();
         
          WebPWriteParam writeParam = new WebPWriteParam(writer.getLocale());
          
          writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
          //Set lossy compression
          writeParam.setCompressionType(writeParam.getCompressionTypes()              [WebPWriteParam.LOSSY_COMPRESSION]);

          //Set 80% quality.
          writeParam.setCompressionQuality(0.1f);

          // Save the image
          writer.setOutput(new FileImageOutputStream(new File("filePath")));

          writer.write(null, new IIOImage(image, null, null), writeParam);
          
        System.out.println("Complete");
        
        
    } catch (FileUploadException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

So how can I directly get byte array of compressed WebP without saving the file?

J K
  • 1
  • 1
  • 1
    Use `ByteArrayOutputStream`? – g00se Apr 12 '23 at 13:17
  • 1
    This is basically the same Q/A as here: https://stackoverflow.com/a/37726626/1428606, just a different output format (it uses `ByteArrayOutputStream`). – Harald K Apr 12 '23 at 13:24
  • Maybe `ByteArrayOutputStream baos = new ByteArrayOutputStream();writer.setOutput(new MemoryCacheImageOutputStream(baos));` – g00se Apr 12 '23 at 13:24

0 Answers0