3

I'm looking for a way in scala to detect the mimetype of an image as Array[Byte]. Are there any good libraries for this in scala?

br dan

sonix
  • 243
  • 2
  • 17
  • 1
    use the java libraries: http://stackoverflow.com/questions/51438/getting-a-files-mime-type-in-java – flavian Mar 20 '14 at 13:47
  • 2
    unfortunately I don't have a path but just the bytearray and I don't want to save the image before a validation. – sonix Mar 20 '14 at 14:31
  • @sonix, if you look further than the accepted answer you'll see that there are methods to detect file type using a stream of data. That's what you need. – Vladimir Matveev Mar 20 '14 at 14:48

1 Answers1

3

thanks.

I used the following code to solve the problem

 def detectMimeType(bytes: Array[Byte]): Either[String, String] = {
    val c1 = if (bytes.length >= 1) bytes.apply(0) & 0xff else 0x00
    val c2 = ...

    if (c1 == 'G' && c2 == 'I' && c3 == 'F' && c4 == '8')
       Right("image/gif")
    else if (c1 == 137 && c2 == 80 && c3 == 78 && c4 == 71 && c5 == 13 && c6 == 10 && c7 == 26 && c8 == 10)
       Right("image/png")
    else if (c4 == 0xEE && c1 == 0xFF && c2 == 0xD8 && c3 == 0xFF)
      Right("image/jpg")
    else if (c1 == 0xFF && c2 == 0xD8 && c3 == 0xFF)
      Right("image/jpeg")
    else
      Left("unknown/unknown")
  }
sonix
  • 243
  • 2
  • 17