我正在使用php gd调整图片大小。结果是我想要上传到Amazon S3的图像资源。如果我先将图像存储在磁盘上,它可以很好地工作,但我希望直接从内存中上传它们。只要我知道图像的字节大小,就可以实现这一点。
有没有办法获得gd图像资源的大小(以字节为单位)?
您可以使用PHP的内存I/O流将图像保存,然后获取以字节为单位的大小。
您需要执行以下操作:
$img = imagecreatetruecolor(100,100);
// do your processing here
// now save file to memory
imagejpeg($img, 'php://memory/temp.jpeg');
$size = filesize('php://memory/temp.jpeg');
现在你应该知道尺寸大小了。
我不知道任何(使用gd)方法来获取图像资源的大小。
我无法使用imagepng函数将内容写入php://memory,因此我使用ob_start()、ob_get_content()和ob_end_clean()。
$image = imagecreatefrompng('./image.png'); //load image
// do your processing here
//...
//...
//...
ob_start(); //Turn on output buffering
imagejpeg($image); //Generate your image
$output = ob_get_contents(); // get the image as a string in a variable
ob_end_clean(); //Turn off output buffering and clean it
echo strlen($output); //size in bytes
ob_get_length
呢? - Wilt$img = imagecreatetruecolor(100,100);
// ... processing
ob_start(); // start the buffer
imagejpeg($img); // output image to buffer
$size = ob_get_length(); // get size of buffer (in bytes)
ob_end_clean(); // trash the buffer
现在,$size
将显示你的大小(以字节为单位)。
将图像文件以所需格式保存到临时目录中,然后在从磁盘上传到S3之前使用filesize() http://php.net/manual/de/function.filesize.php。
gd
函数需要一个路径而不是文件资源来进行写入。但是,可以使用输出缓冲来解决这个问题。 - decezephp://memory/resource=img.jpeg
。 - Dennis Haarbrink