使用PHP生成多个图像 [英] Generate multiple images with PHP

查看:130
本文介绍了使用PHP生成多个图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码

$files = scandir("images");
$exclude = array(".", "..");

$images = array_diff($files, $exclude);

foreach($images as $image) {

    $original_image  = imagecreatefromjpeg("images/{$image}");
    $original_width  = imagesx($original_image);
    $original_height = imagesy($original_image);

    $new_width  = 180;
    $new_height = floor($original_height * ($new_width/$original_width));
    $new_image  = imagecreatetruecolor($new_width, $new_height);

    imagecopyresampled($new_image, $original_image, 0, 0, 0, 0, $new_width, $new_height, $original_width, $original_height);

    header("Content-Type: image/jpeg");

    imagejpeg($new_image);
}

问题

代码的调整大小部分工作正常,但它只输出第一个调整大小的图像。我如何才能使它转储所有已调整大小的图像?

The resizing part of the code works just fine, but it only outputs the first resized image. How can I make it so that it dumps all of the resized images?

推荐答案

你不能这样做正在做。 imagejpeg 打印图像的字节(这就是为什么,结合正确的标题,您可以在浏览器中看到该图片)。但是,打印多个图像(以及尝试更改标题)将无法正常工作,因为您正在修改第一个图像的字节,而不是将新图像附加到输出。如果你想使用这样的解决方案,你可以:

You can't do such the way you are doing it. imagejpeg "prints" the bytes of the image (which is why, combined with the proper header, you see that picture in your browser). However, printing multiple images (plus trying to change the header) won't work, as you are "modifying" the bytes of the first image, and not appending new images to the output. If you want to use a solution like that, you could:


  1. 保存服务器中的每个图像,然后访问这些图像另一种方式(通过打印< img> 标签指向图片或投放某种列出图像的结构)。

  1. Save every image in your server and then access those images in another way (either by printing <img> tags pointing to the pictures or throwing some kind of structure listing the images).

如果您不想保存它们,您始终可以使用base64对字节进行编码,然后将其用作< img src>

If you don't want to save them, you can always encode the bytes using base64 and then using that as an <img src>:

ob_start ();
imagejpeg ($new_image);
$image_data = ob_get_contents ();
ob_end_clean ();
$image_data_base64 = base64_encode ($image_data);
echo '<img src="data:image/jpg;base64,'.$image_data_base64.'" />';


你应该每次都这样做。

非常重要:输出后总是使用 imagedestroy($ new_image)使用)PHP中的图像对象:它将释放资源,因此您不会收到容易的内存耗尽错误。

And very important: always use imagedestroy($new_image) after outputting (or finishing your work with) an image object in php: it will release resources, so you won't receive a "Memory exhausted" error that easy.

这篇关于使用PHP生成多个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆