在Java中获取Mathematica图像

5

我正在尝试使用J/Link将一张图片从Mathematica传到Java。我可以在Mathematica中像这样打印出这张图片:

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

我尝试以不同的方式从Mathematica函数中返回数据:

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]] ];

我的Java代码:

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");
}

在调试时,我得到了一个大的字节数组res。尽管图像确实被保存了,但是它是空白的(即一张白色的图像)。

如果我只返回一个字符串(“blue”),则会保存带有字符串“blue”的图像。

我猜想我需要在renderImageGeneric中以不同的方式返回一些东西,但我无法弄清楚应该返回什么。

谢谢!

2个回答

2

我没能正确地从函数中获取返回值。不过,我改变了方法,让Mathematica将图像输出到文件中。我向Mathematica函数传递了路径,这样Java就知道它在哪里了。虽然不是最好的解决方案,但它能解决问题。


0

你试过类似以下的代码吗?

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

那个也不行。我不确定出了什么问题,但是JLink似乎无法正确评估函数的返回结果。 - rmw

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接