0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【コピペでできる】Kotlinで画像合成

Last updated at Posted at 2024-09-27

はじめに

Kotlinで画像を任意のテキストと合成しその結果を出力したい場合、以下のようにするとよいです

ディレクトリ構成

以下のような構成にする
今回はDockerを使ってやってみる。Main.jarはコンパイル時にできるものなので作成しなくて良い
スクリーンショット 2024-09-28 2.09.51.png

ソースコード

Dockerfile
FROM zenika/kotlin
# 作業ディレクトリを作成
WORKDIR /app

# プロジェクトファイルをコンテナにコピー
COPY . .

CMD ["sh", "-c", "kotlinc Main.kt -include-runtime -d Main.jar && java -jar Main.jar"]
Main.kt
import java.awt.*
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO

fun addTextToImage(imagePath: String, outputPath: String, text: String) {
    // 画像を読み込む
    val imageFile = File(imagePath)
    val image: BufferedImage = ImageIO.read(imageFile)

    // 描画用に新しいBufferedImageを作成
    val outputImage = BufferedImage(image.width, image.height, BufferedImage.TYPE_INT_ARGB)
    val graphics = outputImage.createGraphics()

    // 元の画像を描画
    graphics.drawImage(image, 0, 0, null)

    // テキストのスタイルを設定
    val font = Font("Arial", Font.BOLD, 48)  // フォントとサイズを設定
    graphics.font = font
    graphics.color = Color.WHITE  // テキストの色

    // テキストの位置を計算(右下に配置)
    val fontMetrics = graphics.fontMetrics
    val x = image.width - fontMetrics.stringWidth(text) - 20  // 右下に余白を作るためのマージン
    val y = image.height - fontMetrics.height + fontMetrics.ascent - 20

    // テキストを画像に描画
    graphics.drawString(text, x, y)

    // リソースを解放
    graphics.dispose()

    // 結果を保存
    val outputFile = File(outputPath)
    ImageIO.write(outputImage, "png", outputFile)
    
}

fun main() {
    val imagePath = "input_image.png"  // 入力画像のパス
    val outputPath = "output_image.png"  // 出力画像の保存先
    val text = "Sample Text"  // 合成するテキスト

    addTextToImage(imagePath, outputPath, text)

    println("テキストを追加した画像を保存しました: $outputPath")
}

実行

以下コマンドを実行しビルド

docker build -t kotlin-image-processing .

以下コマンドを実行し合成された画像を出力

docker run --rm -v $(pwd):/app kotlin-image-processing

input_image.pngに「Sample Text」が合成されてoutput_image.pngに出力されました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?