Skip to content

Commit

Permalink
Add exceptions to the convertHexToImage function to check that the ar…
Browse files Browse the repository at this point in the history
…gument is as expected (Hexadecimal String).
  • Loading branch information
Antonio171003 committed Sep 6, 2024
1 parent d645f56 commit df59cda
Showing 1 changed file with 9 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,17 @@ object Images {
}

def convertHexToImage(imageHex: String): String = {
// Remove the "0x" prefix from the hex string, as it's not part of the actual image data
// Check if the argument is a hexadecimal string"
if (!imageHex.startsWith("\\x") || (imageHex.length % 2) == 1) {
throw new IllegalArgumentException(s"Error: Expected a hexadecimal string but found: $imageHex")
}
// Remove the "\x" prefix from the hex string, as it's not part of the actual image data
val hex = imageHex.tail.tail
val imageBinary: Array[Byte] =
if ((hex.length % 2) == 1)
Array.empty
else
Try(hex.grouped(2).map { hex => Integer.parseInt(hex, 16).toByte }.toArray) match {
case Success(value) => value
case Failure(_) => Array.empty
}
Try(hex.grouped(2).map { hex => Integer.parseInt(hex, 16).toByte }.toArray) match {
case Success(value) => value
case Failure(_) => Array.empty
}
val byteArray = Uint8Array(js.Array(imageBinary.map(_.toShort): _*))
dom.URL.createObjectURL(dom.Blob(js.Array(byteArray.buffer)))
}
Expand Down

0 comments on commit df59cda

Please sign in to comment.