Wednesday, March 19, 2014

Saving an image in Cassandra BLOB field

We had an occasion today to be able to store images in a blob field of a Cassandra tables.  More to the point I needed to extract it and send it from a java servlet to a web browser as an image.   The code for storing the image is quit easy but there is a small gotcha when retrieving it.   So, suppose we have a table that looks something like:

String CreateTweetTable = "CREATE TABLE if not exists Messages ("+
                "user varchar,"+
                " interaction_time timeuuid,"+
                " tweet varchar,"+
                " image blob," +
                " imagelength int,"+
                " PRIMARY KEY (user,interaction_time)"+
                ") WITH CLUSTERING ORDER BY (interaction_time DESC);";

Our image will be in the blob field and we also store the size of the image for reference. We can load a picture from a file on the local machines hard disk like this:

FileInputStream fis=new FileInputStream("/Users/Administrator/Desktop/mystery.png");
byte[] b= new byte[fis.available()+1];
int length=b.length;
fis.read(b);

We now need to convert the byte array into a bytebuffer:

ByteBuffer buffer =ByteBuffer.wrap(b);

Writing the record becomes simply:

 PreparedStatement ps = session.prepare("insert into Messages ( image, user, interaction_time,imagelength) values(?,?,?,?)");
BoundStatement boundStatement = new BoundStatement(ps);
session.execute(  boundStatement.bind( buffer, "Andy",  convertor.getTimeUUID(),length));


Getting the image back is simple.  Use a Select to get the result set:

PreparedStatement ps = session.prepare("select user,image,imagelength from Messages where user =?");
BoundStatement boundStatement = new BoundStatement(ps);
ResultSet rs =session.execute ( boundStatement.bind("Andy"));

We can now loop through the result set (here we are assuming only one image comes back)

ByteBuffer bImage=null;
for (Row row : rs) {
 bImage = row.getBytes("image") ;
 length=row.getInt("imagelength");
}

However to display the image we will need it as a byte array.  We can’t use bImage.get() as this reaches down in to the raw buffer (see: https://groups.google.com/a/lists.datastax.com/forum/#!searchin/java-driver-user/blob$20ByteBuffer/java-driver-user/4_KegVX0teo/2OOZ8YOwtBcJ for details )  Instead we can use :

byte image[]= new byte[length];
image=Bytes.getArray(bImage);

In the servlet we can return this image in one of 2 ways:

OutputStream out = response.getOutputStream();
response.setContentType("image/png");
response.setContentLength(image.length);
out.write(Image);

Writes the image as a single lump which may use too much memory.  You might be better using a bufferedinput stream (http://stackoverflow.com/questions/2979758/writing-image-to-servlet-response-with-best-performance

InputStream is = new ByteArrayInputStream(Image);
BufferedInputStream input = new BufferedInputStream(is);
byte[] buffer = new byte[8192];
for (int length = 0; (length = input.read(buffer)) > 0;) {
    out.write(buffer, 0, length);
}
out.close();

29 comments:

  1. I would like to thank you for the efforts you have made in writing this article.
    Signature:
    Versión en descargar facebook en español a los países hablan Español: facebook entrar agora , facebook en español para and facebook entrar direto

    ReplyDelete
  2. Very helpful advice in this particular post! It’s the little changes that make the largest changes. Thanks for sharing!
    Signature:
    The place to play all unblockedgames online. Here you can find every blocked games such as: unblocked games , unblocked games happy , unblocked games 77 , Gmod Free

    ReplyDelete
  3. I was having discussion about this yesterday with a friend of mine, he works as a developer in http://webxity.com and he was telling me the same thing and I was saying to him that he is wrong :)
    #SorryMyFriend

    ReplyDelete
  4. This is a really good read for me, Must admit that you are one of the best bloggers I ever saw.
    Web Design Rochester NY
    Web Designing Rochester NY
    Web Development Rochester NY

    ReplyDelete
  5. You need to kill time, you need entertainment. Refer to our website. hope you get the most comfort.
    Thanks you for sharing!
    Friv 4

    ReplyDelete
  6. Play the Best Free Games! We've picked out the racing games, cooking games, candy crush, games shooting, fashion games, ...
    Thanks for sharing !
    Kizi 200
    Friv 1
    Y88
    Y9

    ReplyDelete
  7. Thanks. I will show it to our guys in website

    ReplyDelete
  8. Youth was standing in that place he kept saying not stop, you ever hear such side stop, but you never have the courage to move forward, kissed the lips of her beautiful.
    musicas download , snapchat download , geometry dash online , run , b612

    ReplyDelete
  9. Thank you for sharing valuable information. Nice post. I enjoyed reading this post.Old Age Home in Coimbatore, Charitable Trust in Coimbatore


    ReplyDelete
  10. All are saying the same thing repeatedly, but in your blog I had a chance to get some useful and unique information, I love your writing style very much, I would like to suggest your blog in my dude circle, so keep on updates.

    Dataware Housing Training in Chennai

    ReplyDelete
  11. Thank you for sharing valuable information. Nice post. I enjoyed reading this post.Hotels in Kumbakonam,Budget Hotels in Kumbakonam

    ReplyDelete
  12. Thank you for sharing such a nice and interesting blog with us. I have seen that all will say the same thing repeatedly. But in your blog, I had a chance to get some useful and unique information. I would like to suggest your blog in my dude circle.
    Isoft Innovations Company Address
    Isoft Innovations Facebook

    ReplyDelete
  13. The blog is absolutely truly incredible. Lots of large information and inspiration, both of which we all need.


    Bangalore Web Designing Company, Web Development Company in Bangalore

    ReplyDelete
  14. Very useful article about seo concepts..It is very easy to understand about seo for beginerrs and learners..kepp posting useful posts like this..Hotels in Kumbakonam,Kumbakonam Hotels

    ReplyDelete
  15. cool, really useful tips, I know it

    ReplyDelete
  16. Very useful article about seo concepts..It is very easy to understand about seo for beginerrs and learners..kepp posting useful posts like this..SPA IN KUMBAKONAM, SPA IN TRICHY, SPA IN THANJAVUR

    ReplyDelete
  17. This blog is an exact representation of abilities. I realise the blogger for posting the most very good considered. ITFOFINDIA,ITF OF INDIA

    ReplyDelete
  18. Thank you for sharing such an informative news with us. Keep on sharing Contents like this. You can also share this content on various sites like the Automation Associates LLC site.

    ReplyDelete
  19. The post is very informative. It is a pleasure reading it. I have also bookmarked you for checking out new posts. You can also share this valuable content on other platforms such as Blogspot, the famous Wordpress site, the innovative Tumblr site and also the sites like Medium and the famous Live Journal site.

    ReplyDelete
  20. Thank you for sharing this information. Come back again for more interesting stuff like this post. You can share this informative post in Social Media sites like the worldwide famous Facebook, the all-time favorite Twitter and the most interesting Google Plus site, business site LinkedIn and also to the Infographic site Pinterest to generate more traffic to your blog post.

    ReplyDelete
  21. I have analyzed your post. Excellent details you did here. I enjoyed reading your blog, and it is both instructional and enjoyable. Share this most interesting post in other sites like OS Business Opportunities, the innovative Asaim Japan site and also to the Jfissures site followed by Free Samples 411 and lastly to the sites like Johny Adams sites.

    ReplyDelete
  22. Thank you for sharing this excellent post. The post is handy and useful. You can also share these type of posts in the platforms like Wordpress, the famous Blogspot site, the all favorite Tumblr site and also in the location like Medium and lastly to the Live Journal site.

    ReplyDelete
  23. This is the kind of post I was searching for today. Awesome post and very useful and easy to read. Thank you for sharing this wonderful; post. You can also share these post on the Social media's like Google Plus, the all time hit Facebook, the notorious Twitter, the business sharing site LinkedIn and lastly to the famous Infographic site Pinterest to gain more traffic to your blog post.

    ReplyDelete

  24. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic.


    Pawn Shop

    Pawn Loans

    Pawn Shops

    Pawn Loan

    Pawn Shop near me

    ReplyDelete
  25. Thank you for sharing valuable information. Nice post. I enjoyed reading this postweb design company in kerala

    ReplyDelete