Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public final class MediaHelper {
return null;
}

if (mimeType.startsWith("image/")) {
if (isSupportedImage(inputFile, mimeType)) {
if (isImageCompliant(inputFile, mimeType)) {
LOGGER.atInfo().log("The image doesn't need conversion");
return null;
Expand Down Expand Up @@ -288,6 +288,46 @@ private static boolean isAnimationCompliant(@Nullable AnimationDetails animation
&& animation.height() == MAX_SIDE_LENGTH;
}

/**
* Checks if the MIME type corresponds to one of the supported image formats.
* If the image file is an animated WebP, {@code false} is returned as they are not currently supported.
*
* @param image the image file to check
* @param mimeType the MIME type to check
* @return {@code true} if the MIME type is supported
*/
private static boolean isSupportedImage(File image, String mimeType) {
if ("image/webp".equals(mimeType) && isAnimatedWebp(image)) {
LOGGER.atInfo().log("The image is an animated WebP");
return false;
}

return mimeType.startsWith("image/");
}

/**
* Detects if a WebP file is animated by checking its file header.
*
* @param file the WebP file to check
* @return {@code true} if the file is an animated WebP
*/
private static boolean isAnimatedWebp(File file) {
try (var fileInputStream = new FileInputStream(file)) {
var header = new byte[256];
int bytesRead = fileInputStream.read(header);

if (bytesRead < 32) {
return false;
}

var headerContent = new String(header, UTF_8);
return headerContent.contains("ANIM");
} catch (IOException e) {
LOGGER.atWarn().setCause(e).log("An error occurred checking if the file is an animated WebP");
return false;
}
}

/**
* Checks if passed-in image is already compliant with Telegram's requisites.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ void resizeAnimatedWebpVideo() {
var webpVideo = loadResource("animated.webp");

var ex = assertThrows(MediaException.class, () -> MediaHelper.convert(webpVideo));
assertThat(ex.getMessage(), equalTo("FFmpeg image conversion failed"));
assertThat(ex.getMessage(), equalTo("The file with image/webp MIME type is not supported"));
}

@Test
Expand Down
Loading