Skip to content

Commit

Permalink
ImageUtil.java: Ensure we remove the alpha channel when writing scree…
Browse files Browse the repository at this point in the history
…nshots

This is due to the output screenshots being in a JPG format, this small function ensures that the output BufferedImage doesn't include an alpha channel.
  • Loading branch information
ProjectSynchro committed Sep 10, 2024
1 parent a074ac0 commit f714efb
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/main/java/tools/sctrade/companion/utils/ImageUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,25 @@ public static void writeToDiskNoFail(BufferedImage image, Path path) {
static void writeToDisk(BufferedImage image, Path path) throws IOException {
Files.createDirectories(path.getParent());
File imageFile = new File(path.toString());
String format = path.toString().substring(path.toString().lastIndexOf(".") + 1);

// Get the format from the file extension
String format = path.toString().substring(path.toString().lastIndexOf(".") + 1).toLowerCase();

// If the format is JPG, ensure no alpha channel is present
if ("jpg".equals(format) || "jpeg".equals(format)) {
if (image.getTransparency() != BufferedImage.OPAQUE) {
image = convertToJpgCompatible(image);
}
}

// Write the image to disk in the desired format
ImageIO.write(image, format, imageFile);
}

// Helper method to convert an image to a JPG-compatible format (no alpha channel)
private static BufferedImage convertToJpgCompatible(BufferedImage image) {
BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
newImage.createGraphics().drawImage(image, 0, 0, null);
return newImage;
}
}

0 comments on commit f714efb

Please sign in to comment.