Skip to content

Instantly share code, notes, and snippets.

Embed
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 java.io.IOException;
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
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 = ImageIO.read(bis);
bis.close();
} catch (Exception e) {
e.printStackTrace();
}
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);
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
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 = ImageIO.read(new File("/Users/davidfauth/Downloads/pig_python_elasticsearch.png"));
BufferedImage newImg;
String imgstr;
imgstr = encodeToString(img, "png");
System.out.println(imgstr);
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);
tx.success();
}
graphDb.shutdown();
/* 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