LoginSignup
5
3

More than 5 years have passed since last update.

kotlinで画像ファイルをリサイズする

Posted at

Imagemagickなどの外部ツールを使わずにサムネイル画像なんかをリサイズしたかったので、標準ライブラリだけの実装例です。

実装

こちらの記事で紹介されていたJavaによる例を参考に、kotlinで実装しました。
Intで圧縮後のファイルの幅を指定しています。

    fun resize(): ByteArray {
        // この変数に画像ファイルをByteArrayで読み込んでおく
        val imageFile :ByteArray
             val width = 200

        // オリジナルのファイルを読み込む
        val original = ImageIO.read(ByteArrayInputStream(imageFile)) ?: throw Exception("File is invalid")
        val originalWidth  = original.width.toDouble()
        val originalHeight = original.height.toDouble()

        // リサイズ後のファイルを作成
        val resizedWidth  = width.toDouble()
        val resizedHeight = width * originalHeight / originalWidth
        val resized = BufferedImage(resizedWidth.roundToInt(), resizedHeight.roundToInt(), original.type)

        // 変換器
        val transformer = AffineTransformOp(
                AffineTransform.getScaleInstance( resizedWidth / originalWidth, resizedHeight / originalHeight)
                , AffineTransformOp.TYPE_BILINEAR
        )

        // 変換
        transformer.filter(original, resized)

        // 変換した結果を書き込む
        val result = ByteArrayOutputStream()
        ImageIO.write(resized, "jpg", result)

        return result.toByteArray()
    }

実際に使用するにはもう少し細かい作り込みが必要かもしれませんが、とりあえず動くところまで。

参考

Java で画像サイズを変更する
https://docs.oracle.com/javase/tutorial/2d/images/saveimage.html

5
3
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
5
3