This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package rJava; | |
import java.io.File; | |
import java.io.IOException; | |
import java.nio.file.Files; | |
import java.util.Base64; | |
import org.rosuda.JRI.Rengine; | |
public class RSample { | |
public static void main(String[] args) throws IOException { | |
Rengine engine = new Rengine(new String[] { | |
"--no-save" | |
}, false, null); | |
try { | |
int n = 1000; | |
double[] x = new double[n]; | |
for (int i = 0; i < n; i++) { | |
x[i] = 0.0; | |
for (int j = 0; j < 8; j++) | |
x[i] += Math.random(); | |
x[i] = (x[i] - 4.0); | |
} | |
File file = File.createTempFile("plot", ".png"); | |
file.deleteOnExit(); | |
engine.assign("x", x); | |
engine.eval("png('" + file.getAbsolutePath() + "')"); | |
engine.eval("hist(x, xlim=c(-4,4), ylim=c(0,0.6), prob=T, ann=F, panel.first = grid())"); | |
engine.eval("par(new=T)"); | |
engine.eval("plot(density(x), xlim=c(-4,4), ylim=c(0,0.6), xlab='' , ylab='' , main='' , col='red' )"); | |
engine.eval("dev.off()"); | |
byte[] bytes = Files.readAllBytes(file.toPath()); | |
String encode = (Base64.getEncoder()).encodeToString(bytes); | |
String imageSrc = "data:image/png;base64," + encode; | |
String out = "<html><body><img src=\""; | |
out += imageSrc; | |
out += "\"></body></html>"; | |
System.out.println(out); | |
} finally { | |
engine.end(); | |
} | |
} | |
} |
結果
<html><body><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAeAAAAHgCAYAAAB91L6VAAAD8GlDQ1BJQ0MgUHJvZmlsZQA … IgAALGEUADbJzLUGAQAAEQAIEoEEADHAUvog4gAAIgAALGEfj/xnxImx+sxQYAAAAASUVORK5CYII="></body></html>

0 件のコメント:
コメントを投稿