问题
I am sending an image in base64
format in a json
message
image:["data:image/png;base64,iVBORw...","data:image/png;base64,idfsd..."]
I want to store this image in Cassandra
. This json
maps to my model as an Array[String]
-
case class ImageArray(
image: Array[String]
}
I have read that to store images in cassandra, I need ByteBuffer. So I use ByteBuffer.wrap() to convert the array different indexes of the array into ByteBuffer.
ByteBuffer.wrap(model.image(0).getBytes()) //for the moment, I am taking only 1 image
I am unable to figure out how to conovert the ByteBuffer
back into a String
. I can retrieve the bytes from Cassandra
like follows
(row.getBytes("image"))
The above gives me a ByteBuffer
. How do I convert this into a String
which I could use later to create an Array[String]
回答1:
Though I was able to solve it, the method was very slow so I dropped the idea of storing images as bytes and kept them as string (base64) as that is what I am getting from the server.
Coming to the original issue, to solve the problem, I made a few changes.
Changed Array to List in the model as Cassandra understand Lists
case class ImageArray(
image: List[String]
}
The json array or images mapped to image list by creating a custom Reads
- (JsPath \ "image").read[List[String]]
In cassandra
, the table schema for storing the image arrays was image list<blob>,
Once I had the List in the model, I converted it into List
of String
into List
of Byte
using .value("image",seqAsJavaList(((ByteBuffer.wrap(model.image(0).getBytes())).array().toList):::((ByteBuffer.wrap(model.image(1).getBytes())).array().toList)))
Above, I took the first element of image list (a string which is base64 representation of image at index 0), convert it into byte using ByteBuffer.wrap
, then converted ByteBuffer
to Array
and then converted it to List
. This gave me List[Byte]
for 1st image. I repeat it for image(1) and then join the two images using :::
. Then I convert this Scala
List
to Java
using seqAsJavaList
.
Note: As the above method required multiple conversions, it isn't a optimal way. I instead decided to store the image as List[String]
来源:https://stackoverflow.com/questions/51844961/how-to-store-and-retrieve-base64-encoded-image-in-cassandra