Image Converter — Java source
Convert images between PNG, JPEG and WebP entirely in your browser. Batch-friendly with quality control and a before/after size delta — nothing is uploaded.
This is the Java implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Image converter — Java port of the image-converter tool.
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.stream.ImageOutputStream;
final class ImageConverterTool {
/** Decode -> (JPEG only) flatten onto white -> encode at quality 0..1. */
static byte[] convert(byte[] input, String target, float quality) throws IOException {
BufferedImage src = ImageIO.read(new ByteArrayInputStream(input));
// JPEG has no alpha channel: draw onto an opaque white canvas first,
// or transparent pixels render black in the encoded file.
BufferedImage canvas = "jpeg".equals(target)
? new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_RGB)
: src;
if (canvas != src) {
Graphics2D g = canvas.createGraphics();
try {
g.setColor(Color.WHITE);
g.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
g.drawImage(src, 0, 0, null);
} finally {
g.dispose();
}
}
var writer = ImageIO.getImageWritersByFormatName(target).next();
try (var out = new ByteArrayOutputStream();
var ios = ImageIO.createImageOutputStream(out)) {
var param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality); // 0.85 in the web tool
writer.setOutput(ios);
writer.write(null, new IIOImage(canvas, null, null), param);
return out.toByteArray();
} finally {
writer.dispose();
}
}
public static void main(String[] args) throws IOException {
byte[] png = java.nio.file.Files.readAllBytes(java.nio.file.Path.of(args[0]));
System.out.write(convert(png, "jpeg", 0.85f));
}
}
Also available in 8 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →