php - 使用 GD 库生成 png 图像并将它们添加到 zip 存档
问题描述
我想生成多个.png图像并将它们添加到 zip 存档中以供下载。
我正在使用GD LIBRARY和ZipArchive
这些图像是来自查询的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 调用它)。我没有考虑什么?
谢谢
投资
解决方案
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++;
}
推荐阅读
- javascript - 如何在 reactJS 中使用 emailJS 向特定用户发送电子邮件
- typescript - 使用打字稿在formik错误中键入不匹配错误
- docker - Docker 中的 Nextcloud - 使用端口错误地重新定向 Talk 应用程序
- c# - 使用当前上下文中不存在的未分配局部变量
- github - Cypress 通过 Github 测试与 Xray (Jira) 的集成
- javascript - React Element Type 无效,为什么会出现此错误,如何解决?
- react-native - 如何防止在网页中刷新页面后在 react-native-navigation 中丢失标题返回按钮?
- swift - SwiftUI .sheet 崩溃
- flutter - 如何将新属性添加到颤振/飞镖中的列表项?
- c++ - 在 C++ 中,您可以使用 ToString() 函数将堆栈的内容作为字符串返回吗?