Skip to content

Instantly share code, notes, and snippets.

Created September 16, 2014 18:28
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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