如何在网页上显示由PHP调用的java代码生成的图像?

I have a java jar file that generates an image upon completion. I need to call this from a PHP server. How do I display the image on the web page? exec() or passthru() do not offer features to return images.

If the image returned by Java is a valid image, in PHP you just need to send an additional header using the header() function, so the browser knows it's an image and not regular HTML.

E.g. (presuming the returned image is in JPEG format):

header('Content-Type: image/jpeg');
readfile('path/to/yourimage.jpg');

http://php.net/manual/en/function.header.php

http://php.net/manual/en/function.readfile.php


Another way could be executing the JAR file with the exec() function. Should be something like this:

header('Content-Type: image/jpeg');
exec('java -jar /path/to/file.jar', $output);

http://php.net/manual/en/function.exec.php

I see two possibilities:

  1. Let your Java program write the image file to a location which can be read by your web server. Then you have to separate the image creation and the image retrieving steps.
  2. If your Java program can write the image to standard output, then passthru() should work. To check this, first call your Java program manually and save the output to a file and view the file, for example by java your.jar > test.gif. If this works, use this PHP script to get started:

    <?php
        header('Content-Type: image/gif');
        passthru('java your.jar');
    ?>
    

There might be some problems like the web server having no access to the java executable or to the jar file. If so, try using absolute paths.