Skip to content

Instantly share code, notes, and snippets.

@irbull
Last active July 1, 2020 11:49
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save irbull/9d27185c94f7990570e1882d64140749 to your computer and use it in GitHub Desktop.
Save irbull/9d27185c94f7990570e1882d64140749 to your computer and use it in GitHub Desktop.
package com.eclipsesource.j2v8.tutorial;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.ByteBuffer;
import com.eclipsesource.v8.NodeJS;
import com.eclipsesource.v8.Releasable;
import com.eclipsesource.v8.V8Array;
import com.eclipsesource.v8.V8Object;
import com.eclipsesource.v8.V8TypedArray;
public class Exercise1 {
private static String JIMP_SCRIPT = "var Jimp = require('/Users/irbull/node_modules/jimp');\n"
+ " Jimp.read('/Users/irbull/Downloads/IMG_20160706_175824.jpg', (err, image) => {\n"
+ " if (err) throw err;\n"
+ " process_in_java(image.bitmap.data);\n"
+ " image.write('/Users/irbull/Downloads/output.jpg');\n"
+ " });\n";
public static void main(String[] args) throws IOException {
final NodeJS nodeJS = NodeJS.createNodeJS();
nodeJS.getRuntime().registerJavaMethod((V8Object receiver, V8Array parameters) -> {
V8TypedArray typedArray = (V8TypedArray) parameters.get(0);
ByteBuffer buffer = typedArray.getByteBuffer();
try {
for(int i = 0; i < buffer.limit(); i+=4) {
int gray = createGrayscale(buffer, i);
buffer.put(i, (byte) gray);
buffer.put(i+1, (byte) gray);
buffer.put(i+2, (byte) gray);
};
} finally {
typedArray.release();
}
return null;
}, "process_in_java");
File script = createTemporaryScriptFile(JIMP_SCRIPT, "jimpscript.js");
nodeJS.exec(script);
while(nodeJS.isRunning()) {
nodeJS.handleMessage();
}
nodeJS.release();
}
private static int createGrayscale(ByteBuffer buffer, int i) {
int red = 0xFF & buffer.get(i);
int green = 0xFF & buffer.get(i+1);
int blue = 0xFF & buffer.get(i+2);
int gray = (int) (red + green + blue ) / 3;
return gray;
}
public static void executeJSFunction(V8Object object, String name) {
Object result = object.executeFunction(name, null);
if (result instanceof Releasable) {
((Releasable) result).release();
}
}
public static void executeJSFunction(V8Object object, String name, Object... params) {
Object result = object.executeJSFunction(name, params);
if (result instanceof Releasable) {
((Releasable) result).release();
}
}
private static File createTemporaryScriptFile(final String script, final String name) throws IOException {
File tempFile = File.createTempFile(name, ".js");
PrintWriter writer = new PrintWriter(tempFile, "UTF-8");
try {
writer.print(script);
} finally {
writer.close();
}
return tempFile;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment