🐻‍❄️

[Compose for Desktop]2つの画像を結合して、1つの画像として保存する

2023/04/15に公開1

はじめに

Compose for Desktopを利用してアプリを開発していると2つの画像ファイルを結合して、1つの画像ファイルとして保存するような処理を実装したくなる。。Compose for Desktopを使っている環境で2つの画像ファイルを結合して、1つの画像ファイルとして保存する方法を調べたのでまとめる。

実装方法

以下のようにJavaのImageIOを利用して、2つの画像ファイルを結合して、1つの画像ファイルとして保存する、関数を定義しておく。

fun combine(fileA: File, fileB: File, outputFile: File): Boolean {
    return try {
            val inputA = ImageIO.read(fileA)
            val inputB = ImageIO.read(fileB)
            val totalWidth = inputA.width + inputB.width
            val maxHeight = max(inputA.height, inputB.height)
            val output = BufferedImage(totalWidth, maxHeight, BufferedImage.TYPE_INT_ARGB)

            output.graphics.drawImage(inputA, 0, 0, null)
            output.graphics.drawImage(inputB, inputA.width, 0, null)
            ImageIO.write(output, "PNG", outputFile)

            true
        } catch (e: IOException) {
            false
        }
    }

動作確認

以下のようなFileAとFileBをこの処理に入力すると、OutputFileのような画像が出力されます。この処理では単純に左右に画像を並べていますが、処理を工夫すれば間隔を空けたり、結合するファイルの数を増やすことも、できるかなと思います。

株式会社ゆめみ

Discussion

てべすてんてべすてん

良記事ありがとうございます!

結合する方向(縦か横か)も指定できたらさらに幸せですね!