generate better quality webp thumbnails
authorSvjatoslav Agejenko <svjatoslav@svjatoslav.eu>
Sat, 13 Mar 2021 04:26:00 +0000 (06:26 +0200)
committerSvjatoslav Agejenko <svjatoslav@svjatoslav.eu>
Sat, 13 Mar 2021 04:26:00 +0000 (06:26 +0200)
src/main/java/eu/svjatoslav/meviz/htmlindexer/metadata/fileTypes/Picture.java

index 1f5b272..9604211 100755 (executable)
@@ -17,8 +17,7 @@ import eu.svjatoslav.meviz.htmlindexer.ImageFormatError;
 import eu.svjatoslav.meviz.htmlindexer.Utils;
 import eu.svjatoslav.meviz.htmlindexer.metadata.Dimension;
 
-import javax.imageio.ImageIO;
-import javax.imageio.ImageReader;
+import javax.imageio.*;
 import javax.imageio.stream.FileImageOutputStream;
 import javax.imageio.stream.ImageInputStream;
 import javax.imageio.stream.ImageOutputStream;
@@ -28,8 +27,10 @@ import java.awt.image.BufferedImage;
 import java.awt.image.FilteredImageSource;
 import java.awt.image.ImageFilter;
 import java.awt.image.ImageProducer;
-import java.io.*;
+import java.io.File;
+import java.io.IOException;
 import java.util.ArrayList;
+import java.util.Iterator;
 import java.util.List;
 
 import static eu.svjatoslav.meviz.htmlindexer.Utils.getBufferedImage;
@@ -135,7 +136,6 @@ public class Picture extends AbstractFile {
         final java.awt.Dimension targetDimensions = getTargetThumbnailDimension(
                 sourceImageDimension, preferredTargetDimensions);
 
-        final OutputStream out = new FileOutputStream(outputFile);
 
         final Image scaledImage = scaleImage(inputImage,
                 targetDimensions.width, targetDimensions.height);
@@ -148,8 +148,19 @@ public class Picture extends AbstractFile {
         g.drawImage(scaledImage, 0, 0, null);
         g.dispose();
 
-        ImageIO.write(bufferedImage, "webp", out);
-        out.close();
+
+
+        ImageOutputStream  ios =  ImageIO.createImageOutputStream(outputFile);
+        Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("webp");
+        ImageWriter writer = iter.next();
+        ImageWriteParam iwp = writer.getDefaultWriteParam();
+        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
+        iwp.setCompressionType("Lossy");
+        iwp.setCompressionQuality(0.8f);
+
+        writer.setOutput(ios);
+        writer.write(null, new IIOImage(bufferedImage,null,null),iwp);
+        writer.dispose();
     }
 
     private static void makeGifThumbnail(