Skip to content

Instantly share code, notes, and snippets.

Created September 16, 2014 18:28
Show Gist options
  • Save davidfauth/0991e5ee74a9994b55d9 to your computer and use it in GitHub Desktop.
Save davidfauth/0991e5ee74a9994b55d9 to your computer and use it in GitHub Desktop.
Convert image to base64 and drop into Neo4J
package pe.archty;
* Created by davidfauth on 9/16/14.
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
public class ImageUtils {
* Decode string to image
* @param imageString The string to decode
* @return decoded image
public static BufferedImage decodeToImage(String imageString) throws IOException {
BufferedImage image = null;
byte[] imageByte;
try {
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(imageString);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image =;
} catch (Exception e) {
return image;
* Encode image to string
* @param image The image to encode
* @param type jpeg, bmp, ...
* @return encoded string
public static String encodeToString(BufferedImage image, String type) {
String imageString = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
imageString = encoder.encode(imageBytes);
} catch (IOException e) {
return imageString;
public static void main (String args[]) throws IOException {
/* Test image to string and string to image start */
GraphDatabaseService graphDb;
graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( "/Users/davidfauth/dbPath" );
BufferedImage img = File("/Users/davidfauth/Downloads/pig_python_elasticsearch.png"));
BufferedImage newImg;
String imgstr;
imgstr = encodeToString(img, "png");
newImg = decodeToImage(imgstr);
ImageIO.write(newImg, "png", new File("/Users/davidfauth/Downloads/copy_of_pig_python_elasticsearch.png"));
try (Transaction tx = graphDb.beginTx()) {
Node page = graphDb.createNode(Labels.Page);
page.setProperty("url", "my url2");
page.setProperty("img", imgstr);
/* Test image to string and string to image finish */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment