Getting a Mathematica image in Java

391 views Asked by At

I am attempting to use J/Link to get an image from Mathematica to Java. I am able to print the image in Mathematica like this:

Print[ Graphics[Raster[ img[[1]] ], AspectRatio->Automatic, ImageSize->530 ]  ];

I've tried returning the data from the Mathematica function in various ways:

Return [ Image[Graphics[Raster[ img[[1]] ], AspectRatio->Automatic, ImageSize->530 ]] ];

Return [ Graphics[Raster[ img[[1]] ], AspectRatio->Automatic, ImageSize->530 ] ];

Return [ Raster[ note1[[1]] ] ];

Return [ note1[[1]] ];

My Java code:

ml.evaluate("tmp = renderImageGeneric[" + sampleId + ", noteText," + sizeX + "," + sizeY + ", margin," + dpi + "," + lineStep + "," + tabStep + "," + ligatureMatch + "," + maxLigHeightDiff + "," + mmSearch + "," + highToLowGap + "," + lowToHighGap + "," + wordBaselineVariance + "," + debugFlag + "]");

ml.discardAnswer();
byte[] res = ml.evaluateToImage("tmp", 0, 0);
ByteArrayInputStream strm = new ByteArrayInputStream(res);
BufferedImage imag = ImageIO.read(strm);
//BufferedImage imag = ImageIO.read(new InputStream(res));
if(imag != null) {
      ImageIO.write(imag, "png", new File("/Users/Rebecca/","test.png"));
}else {
      System.out.println("image is null");
}

When debugging, I get a large byte array in res. The image does get saved, but it's blank (i.e. a white image).

If I return just a string ("blue"), an image with the string blue gets saved.

I'm assuming that I need to return something differently in renderImageGeneric, but I can't figure out what.

Thanks!

2

There are 2 answers

0
rmw On BEST ANSWER

I wasn't able to get the return from the function correctly. However, I changed course and had Mathematica output the image to a file. I passed a path to the Mathematica function so that Java would know where it is. Not the best solution but it does the trick.

1
Dr. belisarius On

Did you try somenthing like

     Return[ExportString[Graphics[Disk[], ImageSize -> 100], "PNG"]]