php - 如何使用 ZipArchive 保存 PHP 从 DOCX 获取的图像
问题描述
简要说明:我有一个 Docx 文件。我在 PHP 中完成了一个简单的代码,它提取该文件中的图像并将其显示在页面上。
我想要实现的目标:我希望这些图像应该以相同的名称和格式保存在我的 php 文件旁边。
我的文件夹有sample.docx
(其中有图像),extract.php
(从 docx 中提取图像)和display.php
下面是代码extract.php
<?php
/*Name of the document file*/
$document = 'sample.docx';
/*Function to extract images*/
function readZippedImages($filename) {
/*Create a new ZIP archive object*/
$zip = new ZipArchive;
/*Open the received archive file*/
if (true === $zip->open($filename)) {
for ($i=0; $i<$zip->numFiles;$i++) {
/*Loop via all the files to check for image files*/
$zip_element = $zip->statIndex($i);
/*Check for images*/
if(preg_match("([^\s]+(\.(?i)(jpg|jpeg|png|gif|bmp))$)",$zip_element['name'])) {
/*Display images if present by using display.php*/
echo "<image src='display.php?filename=".$filename."&index=".$i."' /><hr />";
}
}
}
}
readZippedImages($document);
?>
display.php
<?php
/*Tell the browser that we want to display an image*/
header('Content-Type: image/jpeg');
/*Create a new ZIP archive object*/
$zip = new ZipArchive;
/*Open the received archive file*/
if (true === $zip->open($_GET['filename'])) {
/*Get the content of the specified index of ZIP archive*/
echo $zip->getFromIndex($_GET['index']);
}
$zip->close();
?>
我怎样才能做到这一点?
解决方案
我不确定您是否需要像这样多次打开 zip 存档 - 特别是当另一个实例已经打开但我很想尝试以下内容时 - 我应该强调它完全未经测试。
测试后更新:如果您这样做,则无需使用display.php
- 似乎在不同的.docx
文件上工作正常。返回的数据$zip->getFromIndex
产生原始图像数据(所以我发现),因此由于长度原因,无法将其传递到查询字符串中。我试图避免不必要地打开/关闭 zip 存档,因此下面的方法将原始数据添加到输出数组,然后使用这个内联的 base64 编码数据显示图像。
<?php
#extract.php
$document = 'sample.docx';
function readZippedImages($filename) {
$paths=[];
$zip = new ZipArchive;
if( true === $zip->open( $filename ) ) {
for( $i=0; $i < $zip->numFiles;$i++ ) {
$zip_element = $zip->statIndex( $i );
if( preg_match( "([^\s]+(\.(?i)(jpg|jpeg|png|gif|bmp))$)", $zip_element['name'] ) ) {
$paths[ $zip_element['name'] ]=base64_encode( $zip->getFromIndex( $i ) );
}
}
}
$zip->close();
return $paths;
}
$paths=readZippedImages( $document );
/* to display & save the images */
foreach( $paths as $name => $data ){
$filepath=__DIR__ . '/' . $name;
$dirpath=pathinfo( $filepath, PATHINFO_DIRNAME );
$ext=pathinfo( $name, PATHINFO_EXTENSION );
if( !file_exists( $dirpath ) )mkdir( $dirpath,0777, true );
if( !file_exists( $filepath ) )file_put_contents( $filepath, base64_decode( $data ) );
printf('<img src="data:image/%s;base64, %s" />', $ext, $data );
}
?>
推荐阅读
- php - 如何将 ID 从 url 传递到 laravel 中的控制器
- android - 在 Android Studio 中修改计算器
- javascript - 如何在节点js中以JSON解析对象中的函数
- java - 如何使用 poi 将 jtable 保存到 excel 中,包括标题?
- python - 跟踪 BFS 中的节点 - Python、迷宫
- r - 为 R 安装 qiimer 包时出错
- javascript - 身份验证 POST 适用于“请求”但不适用于“节点获取”
- excel - 是否可以立即从表单更新 Excel 单元格,而不需要按下更新按钮?
- java - 如何在休眠中的多对多映射中加入中间表
- javascript - Angular 项目没有运行