|
| 1 | +package net.wiringbits.spra.ui.web.utils |
| 2 | + |
| 3 | +import org.scalajs.dom |
| 4 | +import org.scalajs.dom.{Blob, File} |
| 5 | +import scala.util.{Failure, Success, Try} |
| 6 | +import scala.scalajs.js.Promise |
| 7 | +import scala.scalajs.js.typedarray.{ArrayBuffer, Int8Array, Uint8Array} |
| 8 | +import scala.scalajs.js |
| 9 | + |
| 10 | +object Images { |
| 11 | + def convertImageToByteArray(image: dom.File): js.Promise[String] = { |
| 12 | + new js.Promise[String]((resolve, reject) => { |
| 13 | + val reader = new dom.FileReader() |
| 14 | + reader.onload = { (e: dom.Event) => |
| 15 | + val arrayBuffer = reader.result.asInstanceOf[ArrayBuffer] |
| 16 | + val byteArray = new Int8Array(arrayBuffer).toArray |
| 17 | + resolve(byteArray.mkString("[", ", ", "]")) |
| 18 | + } |
| 19 | + reader.onerror = { (e: dom.Event) => |
| 20 | + reject(new js.Error("Failed to read file")) |
| 21 | + } |
| 22 | + reader.readAsArrayBuffer(image) |
| 23 | + }) |
| 24 | + } |
| 25 | + |
| 26 | + def convertHexToImage(imageHex: String): String = { |
| 27 | + // Remove the "0x" prefix from the hex string, as it's not part of the actual image data |
| 28 | + val hex = imageHex.tail.tail |
| 29 | + val imageBinary: Array[Byte] = |
| 30 | + if ((hex.length % 2) == 1) |
| 31 | + Array.empty |
| 32 | + else |
| 33 | + Try(hex.grouped(2).map { hex => Integer.parseInt(hex, 16).toByte }.toArray) match { |
| 34 | + case Success(value) => value |
| 35 | + case Failure(_) => Array.empty |
| 36 | + } |
| 37 | + val byteArray = Uint8Array(js.Array(imageBinary.map(_.toShort): _*)) |
| 38 | + dom.URL.createObjectURL(dom.Blob(js.Array(byteArray.buffer))) |
| 39 | + } |
| 40 | +} |
0 commit comments