Created
January 23, 2012 20:07
-
-
Save ripper234/1665287 to your computer and use it in GitHub Desktop.
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 ImageCreator { | |
private ImageCreator(){} | |
private final static String FONT = "Freestyle Script"; | |
public static void main(String[] args) { | |
Path outputFile = Paths.get("c:\\tmp\\img\\test.png"); | |
createFromText("Hello World - this is a long text", outputFile, 150, 50); | |
} | |
/** | |
* <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) { | |
JLabel label = new JLabel(text, SwingConstants.CENTER); | |
label.setSize(width, height); | |
label.setFont(new Font(FONT, Font.BOLD, 24)); | |
BufferedImage image = new BufferedImage( | |
label.getWidth(), label.getHeight(), | |
BufferedImage.TYPE_INT_ARGB); | |
Graphics g = null; | |
try { | |
// paint the html to an image | |
g = image.getGraphics(); | |
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment