【问题标题】:Scala detect mimetype of an Array[Byte] imageScala 检测 Array[Byte] 图像的 mimetype
【发布时间】:2014-04-27 09:47:36
【问题描述】:

我正在寻找一种在 scala 中将图像的 mimetype 检测为 Array[Byte] 的方法。 在 scala 中有什么好的库吗?

br dan

【问题讨论】:

  • 不幸的是我没有路径,只有字节数组,我不想在验证之前保存图像。
  • @sonix,如果您看的比接受的答案更远,您会发现有一些方法可以使用数据流检测文件类型。这就是你所需要的。

标签: image scala mime-types


【解决方案1】:

谢谢。

我用下面的代码解决了这个问题

 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")
  }

【讨论】:

    猜你喜欢
    • 2023-01-21
    • 2014-04-18
    • 1970-01-01
    • 2012-05-15
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 2014-07-21
    相关资源
    最近更新 更多