使用GD Library生成png图像并将其添加到zip存档中

问题描述 投票:1回答:1

我想生成多个。png图像并将其添加到zip存档中以供下载。

我正在使用GD LIBRARYZipArchive

图像是来自查询的foreach循环的文本和图片的组合。

一段代码值得一千个字

require_once '../gd_imagestyle.php';
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {

 foreach($db->query($sql) as $row) { 

  $foto = "../photos/".$row['foto'];
  $ext = pathinfo($foto, PATHINFO_EXTENSION); 

  $my_img = imagecreatetruecolor( 400, 250 );
  $text_colour = imagecolorallocate( $my_img, 0, 0, 0 );

  if($ext == "png"){ // PICTURES CAN BE .png or .jpg
   $thumbnail = imagecreatefrompng($foto);
  }else{
   $thumbnail = imagecreatefromjpeg($foto);
  }

  $tinypic = imagestyle($thumbnail, 'autosize:105 105'); // RESIZE THE PICTURE
  imagecopy($my_img, $tinypic, 270, 85, 0, 0, 105, 105);   // INSERT THE PICTURE
  imagestring( $my_img, 2, 20, 65, "First and last name", $text_colour );
  imagestring( $my_img, 2, 20, 120, "Birthplace", $text_colour );

  imagecolorallocate( $text_color );
  // header( "Content-type: image/png" );  // I COMMENTED THIS PART  SINCE I WANT A ZIP FILE BACK

  imagestring( $my_img, 5, 120, 65, $row['lastname'].' '.$row['firstname'], $text_colour );
  imagestring( $my_img, 5, 120, 120, $row['birthplace'], $text_colour );

  $singleImage = imagepng( $my_img );
  imagedestroy( $my_img );

  $zip->addFile($singleImage, 'newname'.$i.'.png');  // 

  $i++;

 } // END FOREACH

 $zip->close();
} // END ZipArchive

header("Content-Type: application/zip");

服务器显示一个空的.zip(我从另一个页面通过ajax调用它)。我没有考虑什么?

谢谢

投入

php png ziparchive
1个回答
0
投票

ZipArchive不支持添加图像流。您需要将文件写入一个临时位置,然后将其添加到zip中:

$tempPath = '/tmp/';
$i = 0;

foreach($db->query($sql) as $row) {
    $imgStream = imagecreatetruecolor(400, 250);
    // ...more image manipulation of the stream
    $filePath = $tempPath.'temp'.$i.'.png';
    $img = imagepng($imgStream, $filePath);
    $zip->addFile($filePath, 'newfile'.$i.'.png');
    $i++;
}
© www.soinside.com 2019 - 2024. All rights reserved.