首页 > 解决方案 > 如何使用 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();
?>

我怎样才能做到这一点?

标签: php

解决方案


我不确定您是否需要像这样多次打开 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 );
    }
?>

推荐阅读