【问题标题】:Generate png images with GD Library and add them to a zip archive使用 GD 库生成 png 图像并将它们添加到 zip 存档
【发布时间】:2020-02-19 20:21:48
【问题描述】:

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

我正在使用 GD LIBRARYZipArchive

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

一个sn-p值一千个字

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 调用它)。我没有考虑什么?

谢谢

投资

【问题讨论】:

  • 我相信 ZipArchive 需要一个实际的文件才能编写它。您可能需要将图像输出到临时目录,然后添加它。
  • @JeremyHarris 感谢您的评论,我会尝试一下并稍后报告
  • 谢谢@JeremyHarris,我在imagepng() 编辑了我的代码,例如:imagepng($my_img,'./tmp/temporarypic'.$i.'.png'); i> 然后用临时目录的内容重复 $zip->addFile。它有效!
  • 太棒了,我会添加它作为答案:D

标签: php png ziparchive


【解决方案1】:

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++;
}

【讨论】:

    猜你喜欢
    • 2012-03-11
    • 2016-11-07
    • 2015-12-25
    • 2012-03-06
    • 2011-09-07
    • 1970-01-01
    • 2019-11-02
    • 2014-10-17
    • 1970-01-01
    相关资源
    最近更新 更多