PageRenderTime 40ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/scala/proc/MagickRequest.scala

https://github.com/bmatheny/bitshow-tmp
Scala | 107 lines | 74 code | 26 blank | 7 comment | 1 complexity | f3b8d2605e4d0540e60b4cd247bf08d0 MD5 | raw file
  1. package bitshow.proc
  2. import bitshow.{Item, Converter}
  3. import java.io._
  4. import io.Source
  5. import java.lang.StringBuffer
  6. object MagickRequest {
  7. import scala.collection.JavaConverters._
  8. private val environment = System.getenv().asScala
  9. val MAGICK_KEY = "MAGICK_KEY"
  10. val MAGICK_PATH = environment.getOrElse(MAGICK_KEY, "/usr/local/bin/convert")
  11. }
  12. object MagickResize
  13. extends MagickRequest("resize", "-resize 50%")
  14. object MagickBlackAndWhite
  15. extends MagickRequest("blackwhite", "-black -white")
  16. /**
  17. * Unused
  18. */
  19. class ArgStack {
  20. val stringBuffer = new StringBuffer
  21. /** appends a -XXX type option
  22. */
  23. def option(a: String, b:Any) {
  24. stringBuffer.append("-").append(a).append(" ").append(b)
  25. newArg
  26. }
  27. /** adds a bit of space between arguments
  28. */
  29. def newArg {
  30. stringBuffer.append(" ")
  31. }
  32. def arg(a: String) {
  33. stringBuffer.append(a)
  34. newArg
  35. }
  36. def toCommandLine =
  37. stringBuffer.toString
  38. }
  39. class MagickRequest (
  40. val name: String,
  41. val args: String
  42. ) extends Converter {
  43. val BUFFER_SIZE = 1024 * 1024
  44. protected def getConvertPath =
  45. MagickRequest.MAGICK_PATH
  46. private def getTemporaryFile =
  47. File.createTempFile("bitshow", ".png")
  48. private def writeBytesToTemporaryFile(input: InputStream) = {
  49. val bufferedIn = new BufferedInputStream(input)
  50. val outFile = getTemporaryFile
  51. val bufferedOut = new BufferedOutputStream(new FileOutputStream(outFile))
  52. @annotation.tailrec()
  53. def readByte() {
  54. bufferedOut.write(bufferedIn.read)
  55. if(bufferedIn.available() > 0)
  56. readByte()
  57. }
  58. readByte()
  59. bufferedOut.close()
  60. bufferedIn.close()
  61. outFile
  62. }
  63. private def readBytesFromFile(file: File) =
  64. Source.fromFile(file)(scala.io.Codec.ISO8859).map(_.toByte).toArray
  65. def buildCommandLine(inputFile: File, outputFile: File) =
  66. getConvertPath+" "+inputFile.getAbsolutePath+" "+args+" "+outputFile.getAbsolutePath
  67. def execute(inputFile: File, outputFile: File): Int = {
  68. import scala.sys.process._
  69. (buildCommandLine(inputFile, outputFile)) !
  70. }
  71. def execute(inputFile: String, outputFile: String): Int =
  72. execute(new File(inputFile), new File(outputFile))
  73. def execute(input: InputStream): Array[Byte] = {
  74. val inputFile = writeBytesToTemporaryFile(input)
  75. val outputFile = getTemporaryFile
  76. val exitCode = execute(inputFile, outputFile)
  77. readBytesFromFile(outputFile)
  78. }
  79. def apply(item: Item) =
  80. item
  81. }