Skip to content

Instantly share code, notes, and snippets.

@tgrall
Created June 3, 2013 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgrall/5698193 to your computer and use it in GitHub Desktop.
Save tgrall/5698193 to your computer and use it in GitHub Desktop.
Storing an image in Couchbase using Java SDK
package com.couchbase.devday;
import com.couchbase.client.CouchbaseClient;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
public class SampleStoreImage {
private static final Logger logger = Logger.getLogger(ex10StoreImage.class.getName());
private static CouchbaseClient cb = null;
public static void main(String[] args) {
List<URI> uris = new LinkedList<URI>();
uris.add(URI.create("http://127.0.0.1:8091/pools"));
try {
cb = new CouchbaseClient(uris, "default", "");
saveImageInCouchbase();
extractImageFromCouchbase();
cb.shutdown(10, TimeUnit.SECONDS);
} catch (Exception e) {
System.err.println("Error : " + e.getMessage());
}
}
private static void saveImageInCouchbase() throws Exception {
BufferedImage image = ImageIO.read(new File("/Users/tgrall/Downloads/image.png"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( image, "png", baos );
baos.flush();
byte[] bytes = baos.toByteArray();
baos.close();
cb.set("myimage", bytes).get();
}
private static void extractImageFromCouchbase() throws Exception {
byte[] bytes = (byte[])cb.get("myimage");
InputStream in = new ByteArrayInputStream(bytes);
BufferedImage buffImage = ImageIO.read(in);
ImageIO.write(buffImage, "png", new File( "/Users/tgrall/Downloads/image-2.png" ));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment