16進数文字列から画像に変換する方法(Kotlin)


https://so-wh.at/entry/20041012/p1
上記のページを参考にしました。もしかしたら他の方が書いているかもしれませんが自分用メモとして。

前提として、画像を16進文字列に変換したテキストファイルをアセットに保管してあります。


fun hextoBitmap(file: String): Bitmap {
        val openfile = assets.open(file)
        var imagetext = ""
        try {
            val inst = InputStreamReader(openfile)
            val br = BufferedReader(inst)
            var line = br.readLine()
            while (line != null) {
                imagetext += line
                line = br.readLine()
            }
            inst.close()
            br.close()
        }catch (e:IOException) {
            Log.e("IOException", e.toString())
        }

        val bytes = mutableListOf<Byte>()
        for(index in 1..imagetext.length/2) {
            val byte = Integer.parseInt(imagetext.substring((index - 1) * 2,index * 2),16)
            bytes.add(byte.toByte())
        }
        println(bytes)

        val byteArray = bytes.toByteArray()

        val bitmap = BitmapFactory.decodeByteArray(bytearray, 0, byteArray.size)

        return bitmap
    }