Skip to content

Commit

Permalink
add webp support
Browse files Browse the repository at this point in the history
  • Loading branch information
AIDA64S committed Jun 18, 2024
1 parent 52688ff commit 1a39e41
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/main/java/org/teacon/slides/cache/ImageCache.java
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public CompletableFuture<byte[]> getResource(@Nonnull URI location, boolean onli
final HttpCacheContext context = HttpCacheContext.create();
try (CloseableHttpResponse response = createResponse(location, context, online)) {
try {
return IOUtils.toByteArray(response.getEntity().getContent());
return WebpToPng.webpToPng(IOUtils.toByteArray(response.getEntity().getContent()));
} catch (IOException e) {
if (online) {
Slideshow.LOGGER.warn("Failed to read bytes from remote source.", e);
Expand Down
48 changes: 48 additions & 0 deletions src/main/java/org/teacon/slides/cache/WebpToPng.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package org.teacon.slides.cache;

import org.teacon.slides.Slideshow;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.MemoryCacheImageInputStream;
import javax.imageio.stream.MemoryCacheImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Iterator;

public final class WebpToPng {
private static boolean isWebP(byte[] webp) {
if (webp.length < 12) {
return false;
}
boolean isRiff = webp[0] == 'R' && webp[1] == 'I' && webp[2] == 'F' && webp[3] == 'F';
boolean isWebp = webp[8] == 'W' && webp[9] == 'E' && webp[10] == 'B' && webp[11] == 'P';
return isRiff && isWebp;
}

public static byte[] webpToPng(byte[] webp) {
try {
if (!isWebP(webp)) {
return webp;
}
Iterator<ImageReader> imageReader = ImageIO.getImageReadersByFormatName("webp");
if (!imageReader.hasNext()) {
return webp;
}
ImageReader webpReader = imageReader.next();
try (ByteArrayInputStream bais = new ByteArrayInputStream(webp); MemoryCacheImageInputStream inputStream = new MemoryCacheImageInputStream(bais)) {
webpReader.setInput(inputStream);
BufferedImage bufferedImage = webpReader.read(0);
try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); MemoryCacheImageOutputStream outputStream = new MemoryCacheImageOutputStream(baos)) {
ImageIO.write(bufferedImage, "png", outputStream);
outputStream.flush();
return baos.toByteArray();
}
}
} catch (Exception e) {
Slideshow.LOGGER.warn("Failed to convert webp to PNG", e);
return webp;
}
}
}

0 comments on commit 1a39e41

Please sign in to comment.