Is it possible to render pixel-by-pixel identical result with Graphics2D.drawString
on all java platforms with same font? I tried to render text without antialiasing, but results differs on different machines. I use font from project resources, so font is system-independent.
Example of results of same code with same font on two different PCs:
I'm used very small font size (9 px) for clarity.
import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class Test {
public static void main(String... args) throws FontFormatException, IOException {
int x = 0;
int y = 9;
int width = 80;
int height = 10;
float fontSizeInPixels = 9f;
String text = "PseudoText";
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = image.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
URL fontUrl = new URL(
"https://github.com/indvd00m/graphics2d-drawstring-test/blob/master/src/test/resources/fonts/DejaVuSansMono/DejaVuSansMono.ttf?raw=true");
Font font = Font.createFont(Font.TRUETYPE_FONT, fontUrl.openStream());
font = font.deriveFont(fontSizeInPixels);
Color fontColor = Color.BLACK;
Color backgroundColor = Color.WHITE;
graphics.setFont(font);
graphics.setColor(backgroundColor);
graphics.fillRect(0, 0, width, height);
graphics.setColor(fontColor);
graphics.drawString(text, x, y);
ImageIO.write(image, "png", new File("/tmp/test.png"));
}
}
I'm created project for test here:
https://github.com/indvd00m/graphics2d-drawstring-test
Failed build of this project:
https://travis-ci.org/indvd00m/graphics2d-drawstring-test/builds/178672466
Tests passed under openjdk6 and openjdk7 on linux but failed under oraclejdk7 and oraclejdk8 on linux and other OS and java versions.