Created
December 17, 2010 17:59
-
-
Save sidharthkuruvila/745384 to your computer and use it in GitHub Desktop.
Convert some text to an image
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 java.awt.image.BufferedImage | |
import javax.imageio.ImageIO | |
import java.awt.Color | |
import java.io.File | |
import java.awt.Rectangle | |
import java.awt.font.LineBreakMeasurer | |
import java.awt.Graphics2D | |
import java.text.AttributedString | |
import io.Source | |
/** | |
* Convert some text to an image | |
* | |
* Compile the code | |
* scalac TextToImage.scala | |
* | |
* Then run it | |
* scala TextToImage | |
*/ | |
object TextToImage{ | |
def main(args: Array[String]) = { | |
if(args.length != 2) { | |
println("Usage: scala TextToImage input-file output-file") | |
System.exit(0) | |
} | |
val imageHeight = 768 | |
val imageWidth = 1024 | |
val inputFile = args(0) | |
val outputFile = args(1) | |
val text = Source.fromFile(inputFile).mkString | |
val bi = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB) | |
val gr = bi.getGraphics.asInstanceOf[Graphics2D] | |
gr.setColor(Color.white) | |
gr.fill(new Rectangle(0, 0, imageWidth, imageHeight)) | |
gr.setColor(Color.black) | |
writeText(gr, text, 10, 10, imageWidth - 20) | |
val fileType = outputFile.split("[.]").last | |
ImageIO.write(bi, fileType, new File(outputFile)) | |
} | |
def writeText(gr:Graphics2D, text:String, x:Float, y:Float, wrappingWidth:Float){ | |
var y_ = y | |
val lines = text.split("\n") map {line => if(line.length == 0) " " else line} | |
for(line <- lines){ | |
// The following code was copied from | |
// http://download.oracle.com/javase/1.4.2/docs/api/java/awt/font/LineBreakMeasurer.html | |
val it = new AttributedString(line).getIterator | |
val frc = gr.getFontRenderContext | |
val measurer = new LineBreakMeasurer(it, frc) | |
while (measurer.getPosition() < line.length()) { | |
val layout = measurer.nextLayout(wrappingWidth) | |
y_ += layout.getAscent() | |
layout.draw(gr, x, y_) | |
y_ += layout.getDescent() + layout.getLeading() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment