转载请注明出处,如果您觉得文章有用,就点个赞吧!
今天在写图片下载,就想着把可能用的着的方法都汇总下,于是有了下文!
<?php
/**
* @author xyg
*
* 支持下载base64形式的图片
* 支持下载url形式的图片
* 支持http和https图片下载
*
* 暂不支持自主命名文件,后续有时间了再改写
*/
class DownloadPic {
public $base64Data = ''; //base64的图片数据
public $downloadPath = ''; //图片存储路径,以斜杠结尾
public $picUrl = '';
private $filename = ''; //图片名称
private $ext = ''; //后缀
private $schema = ''; //url的协议
private $basename = '';
private const TIMEOUT = 60; //下载超时时间
public function curlPic()
{
$filename = $this->getFullname();
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, self::TIMEOUT);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::TIMEOUT);
curl_setopt($ch, CURLOPT_URL, $this->picUrl);
$data = curl_exec($ch);
curl_close($ch);
$this->downloadPic($data, $filename);
}
public function fileGetPic()
{
$filename = $this->getFullname();
$options = ['http' => ['timeout' => self::TIMEOUT]];
if (strcasecmp($this->schema, 'https') === 0) {
$options = [
'ssl' => ['verify_peer' => false, 'verify_peer_name' => false]
];
}
$stream = stream_context_create($options);
$filedata = file_get_contents($this->picUrl, false, $stream);
$this->downloadPic($filedata, $filename);
}
public function base64DataPic()
{
if (!empty($this->base64Data) && preg_match('#^(data:\s*image/(\w+);base64,)#', $this->base64Data, $match)) {
$ext = $match[2];
$filename = $this->downloadPath . $this->filename . '.' . $ext;
$this->downloadPath(base64_decode(str_replace($match[1], '', $_POST['pics'])), $filename);
} else {
throw new Exception('base64数据为空或者格式不正确');
}
}
private function parseUrl()
{
if (empty($this->picUrl)) {
throw new Exception('下载路径不能为空');
}
list('schema' => $this->schema, 'path' => $path) = parse_url($this->picUrl);
list('extension' => $this->ext, 'filename' => $this->filename, 'basename' => $this->basename) = pathinfo($path);
}
private function getFullname()
{
$this->checkPath();
$this->parseUrl();
return $this->downloadPath . $this->basename;
}
private function downloadPic(string $data, string $filename)
{
if (file_put_contents($filename, $data)) {
return substr($filename, 1);
} else {
throw new Exception('保存数据失败');
}
}
private function checkPath()
{
if (!file_exists($this->downloadPath)) {
mkdir($this->downloadPath, 0755, true);
} else {
if (!is_writeable($this->downloadPath)) {
throw new Exception ('指定下载目录不可读');
}
}
}
}
后面说点啥呢,中国加油 中国科技加油 中国程序猿加油