Created
March 4, 2012 14:56
-
-
Save ripper234/1973391 to your computer and use it in GitHub Desktop.
Different graphics output on linux & Windows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.imageio.ImageIO; | |
import javax.swing.*; | |
import java.awt.*; | |
import java.awt.image.BufferedImage; | |
import java.io.IOException; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
public class Example { | |
/** | |
* <p>Create an image from text. <p/> | |
* <p/> | |
* http://stackoverflow.com/a/4437998/11236 | |
*/ | |
public static void createFromText(String text, Path outputFile, int width, int height, Color color, int fontSize, String fontFamily) { | |
JLabel label = new JLabel(text, SwingConstants.CENTER); | |
label.setFont(new Font(fontFamily, Font.BOLD, fontSize)); | |
label.setSize(width, height); | |
label.setForeground(color); | |
BufferedImage image = new BufferedImage( | |
label.getWidth(), label.getHeight(), | |
BufferedImage.TYPE_INT_ARGB); | |
Graphics2D g = null; | |
try { | |
// paint the html to an image | |
g = (Graphics2D) image.getGraphics(); | |
g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); | |
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); | |
g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); | |
g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE); | |
g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); | |
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); | |
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); | |
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); | |
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); | |
g.setColor(Color.BLACK); | |
label.paint(g); | |
} finally { | |
if (g != null) { | |
g.dispose(); | |
} | |
} | |
// get the byte array of the image (as jpeg) | |
try { | |
ImageIO.write(image, "png", outputFile.toFile()); | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
public static void main(String[] args) { | |
Path output = Paths.get("/tmp/foo.png"); | |
createFromText("Custom Text", output, 200, 40, Color.blue, 30, "Freestyle Script"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment