LoginSignup
1

More than 3 years have passed since last update.

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

Last updated at Posted at 2020-02-14

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
    }


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
1