下载图片并生成压缩包
<?php
/**
* 下载图片并生成压缩包
* @param $data 图片数组,一维
* @param $tmpDir 存放路径
* @return string
*/
public function creatZipImg($data,$tmpDir)
{
if (!file_exists($tmpDir)) {
//创建文件夹
mkdir($tmpDir, 0777, true);
}
$zipName = $tmpDir . '图片-'. date ( 'YmdHis' ) . mt_rand(1000,9999) .'.zip';
// 生成文件
$zip = new \ZipArchive ();
if ($zip->open ($zipName ,\ZipArchive::OVERWRITE) !== true) {
//OVERWRITE 参数会覆写压缩包的文件 文件必须已经存在
if($zip->open ($zipName ,\ZipArchive::CREATE) !== true){
// 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
return '文件夹不存在,请确认';
}
}
foreach($data as $file){
//判断图片是否存在
$isFile = $this->checkFileExists($file);
if (!$isFile){
continue;
}
//抓取图片内容
$fileContent = file_get_contents($file);
//添加图片
$zip->addFromString(basename($file), $fileContent);
}
// 关闭
$zip->close ();
//没有文件
if (!file_exists($zipName)){
return '活动无图片或无法下载,请确认';
}
return $zipName;
}
/**
* 判断文件是否存在,支持本地及远程文件
* @param String $file 文件路径
* @return Boolean
*/
public function checkFileExists($file)
{
// 远程文件
if(strtolower(substr($file, 0, 4))=='http'){
// 远程文件
$header = get_headers($file, true);
return isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'));
}else{
// 本地文件
return file_exists($file);
}
}
/测试
//模拟要导出的图片数组
$data = [
'123.jpg',
'http://baidu.com/45.jpg.com'
];
$dir = '压缩图片/';
$zipName = $this->creatZipImg($data,$dir);
echo zipName;