When trying to add text to an image in Scala, I think the easiest way to implement it is to use the Java standard library. So, basically, the implementation content is almost the same as Java, but I will introduce the sample code together with the referenced site.
There are a few, but I will list the articles that I referred to.
-Scala Documentation --Image processing: Scala image reading / output documentation. -Read a JPEG file with Java, write figures and characters, and output: An implementation that adds characters to images is introduced. I will. -[Java] Image Editing-Combine images vertically and horizontally-: An implementation that combines images with images is introduced. .. -Draw a character string in the [Java] window: The implementation related to font setting is introduced. -Fill background: An implementation that fills the background is introduced. -[Java] Use of anti-aliasing: The implementation of anti-aliasing for characters is introduced. -Change the save quality of JPEG images in Java: The implementation to set the save quality of images is introduced.
This is a sample code that adds characters to the side of the original image and outputs it. While saying Scala, I think it's almost the same as Java.
ImageWritingWordSample.scala
import java.awt.{Color, Font, RenderingHints}
import java.awt.image.BufferedImage
import java.io.{File, FileOutputStream}
import javax.imageio.{IIOImage, ImageIO, ImageWriteParam}
object ImageWritingWordSample extends App {
//Loading the original image
val originalImage = ImageIO.read(new File(s"resources/200x50.png "))
//Incorporate the original image into the new image
val newImage = new BufferedImage(320, 50, originalImage.getType)
val graphics = newImage.createGraphics()
graphics.drawImage(originalImage, 0, 0, null)
//Background color where you write letters
graphics.setColor(Color.WHITE)
graphics.fillRect(200, 0, 320, 50)
//Font settings
graphics.setFont(new Font("Arial", Font.PLAIN, 12))
//Letter color
graphics.setColor(Color.BLACK)
//Antialiasing
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON)
//Add characters
graphics.drawString("Test test", 210,20)
graphics.drawString("Test test", 210,40)
//Image output
val os = new FileOutputStream("resources/new_320x50.jpeg ")
val ios = ImageIO.createImageOutputStream(os)
val writer = ImageIO.getImageWritersByFormatName("jpeg").next
val param = writer.getDefaultWriteParam
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT)
//Image quality settings
param.setCompressionQuality(1.0f)
writer.setOutput(ios)
writer.write(null, new IIOImage(newImage, null, null), param)
writer.dispose()
}
【The original image】 ** [Image after adding characters] **
Recommended Posts