dongpao1905 2013-01-30 14:58
浏览 38

使用PHP生成多个图像

Code

$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);
}

Problem

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?

  • 写回答

2条回答 默认 最新

  • dongzhang6021 2013-01-30 15:14
    关注

    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. 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).

    2. 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.'" />';
      

    You should do so every time.

    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.

    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效