Trying to pull an image off of Amazon S3 (returns S3ObjectInputStream) and send it to the mandrill email api (takes a base64-encoded string). How can this be done in Scala?
3 Answers
I also managed to do it just using the Apache commons; not sure which approach is better, but figured I'd leave this answer for the record:
import org.apache.commons.codec.binary.Base64
import org.apache.commons.io.IOUtils
val bytes = IOUtils.toByteArray(stream)
val bytes64 = Base64.encodeBase64(bytes)
val content = new String(bytes64)
-
I think your answer is better, supposing the apache commons library is available. Feb 7, 2013 at 15:28
Here is one solution, there are probably others more efficient.
val is = new ByteArrayInputStream(Array[Byte](1, 2, 3)) // replace by your InputStream
val stream = Stream.continually(is.read).takeWhile(_ != -1).map(_.toByte)
val bytes = stream.toArray
val b64 = new sun.misc.BASE64Encoder().encode(bytes)
You could (and should) also replace the sun.misc encoder by the apache commons Base64 for a better compatibility.
val b64 = org.apache.commons.codec.binary.Base64.encodeBase64(bytes)
Here's a simple encoder/decoder I wrote that you can include as source. So, no external dependencies.
The interface is a bit more scala-esque:
import io.github.marklister.base64.Base64._
// Same as Lomig Mégard's answer
val b64 = bytes.toBase64