php:如何在不保存到文件的情况下创建一个图像二进制字符串


php : How to create a string of image binary without saving it to a file?

我有一个图像变量

$im = imagecreatetruecolor(400, 300);

有没有办法在不保存到文件的情况下获得jpeg格式的图像的二进制字符串?谢谢

是的,这是可能的(即使没有输出缓冲)。它看起来没有文档,但您可以传递流资源而不是文件名。

<?php
$stream = fopen("php://memory", "w+");
$i = imagecreatetruecolor(200, 200);
imagepng($i, $stream);
rewind($stream);
$png = stream_get_contents($stream);
ob_start();
imagejpeg($im);
$imageString = ob_get_clean();

作为一个函数并添加imagedestroy()

function imagejpeg_tostring($im,$quality=75) {
      ob_start(); //Stdout --> buffer
      imagejpeg($im,NULL,$quality); // output ...
      $imgString = ob_get_contents(); //store stdout in $imgString
      ob_end_clean(); //clear buffer
      imagedestroy($im); //destroy img
      return $imgString;
}