Dax Fohl
Dax Fohl

Reputation: 10781

How do you convert an InputStream to a base64 string in Scala?

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?

Upvotes: 3

Views: 11608

Answers (3)

Mark Lister
Mark Lister

Reputation: 1143

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

Upvotes: 0

Dax Fohl
Dax Fohl

Reputation: 10781

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)

Upvotes: 13

Lomig Mégard
Lomig Mégard

Reputation: 1828

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)

Upvotes: 6

Related Questions