54-gfx-sidebyside.php 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. /*
  3. * Example of calling ImageMagick 'convert' to manipulate an image prior to printing.
  4. *
  5. * Written as an example to remind you to do four things-
  6. * - escape your command-line arguments with escapeshellarg
  7. * - close the printer
  8. * - delete any temp files
  9. * - detect and handle external command failure
  10. *
  11. * Note that image operations are slow. You can and should serialise an EscposImage
  12. * object into some sort of cache if you will re-use the output.
  13. */
  14. require __DIR__ . '/../../vendor/autoload.php';
  15. use Mike42\Escpos\CapabilityProfile;
  16. use Mike42\Escpos\Printer;
  17. use Mike42\Escpos\EscposImage;
  18. use Mike42\Escpos\PrintConnectors\FilePrintConnector;
  19. // Paths to images to combine
  20. $img1_path = dirname(__FILE__) . "/../resources/tux.png";
  21. $img2_path = dirname(__FILE__) . "/../resources/escpos-php.png";
  22. // Set up temp file with .png extension
  23. $tmpf_path = tempnam(sys_get_temp_dir(), 'escpos-php');
  24. $imgCombined_path = $tmpf_path . ".png";
  25. try {
  26. // Convert, load image, remove temp files
  27. $cmd = sprintf(
  28. "convert %s %s +append %s",
  29. escapeshellarg($img1_path),
  30. escapeshellarg($img2_path),
  31. escapeshellarg($imgCombined_path)
  32. );
  33. exec($cmd, $outp, $retval);
  34. if ($retval != 0) {
  35. // Detect and handle command failure
  36. throw new Exception("Command \"$cmd\" returned $retval." . implode("\n", $outp));
  37. }
  38. $img = EscposImage::load($imgCombined_path);
  39. // Setup the printer
  40. $connector = new FilePrintConnector("php://stdout");
  41. $profile = CapabilityProfile::load("default");
  42. // Run the actual print
  43. $printer = new Printer($connector, $profile);
  44. try {
  45. $printer -> setJustification(Printer::JUSTIFY_CENTER);
  46. $printer -> graphics($img);
  47. $printer -> cut();
  48. } finally {
  49. // Always close the connection
  50. $printer -> close();
  51. }
  52. } catch (Exception $e) {
  53. // Print out any errors: Eg. printer connection, image loading & external image manipulation.
  54. echo $e -> getMessage() . "\n";
  55. echo $e -> getTraceAsString();
  56. } finally {
  57. unlink($imgCombined_path);
  58. unlink($tmpf_path);
  59. }