<?php
/**
* Describe: 图片转base64
* 使用方法: php imgtobase64.php path=/www/projects/test/20220623171931.png
* Author: ZhaoGuibin
* Date: 2022-06-23
*/
class ImgToBase64
{
static private $instance;
private function __construct()
{
}
static public function getInstance()
{
if (!self::$instance instanceof self) {
self::$instance = new self();
}
return self::$instance;
}
/**
* 获取命令行输入参数
* @return array
*/
function getClientArgs()
{
global $argv;
array_shift($argv);
$args = array();
array_walk($argv, function ($v, $k) use (&$args) {
@list($key, $value) = @explode('=', $v);
$args[$key] = $value;
});
return $args;
}
/**
* 图片转为base64
* @param $img_path
* @return string|void
*/
function imgToBase64($img_path = '')
{
$img = isset($img_path['path']) ? $img_path['path'] : '';
if (!$img) {
return '图片不存在或图片路径不正确';
}
if ($fp = fopen($img, "rb", 0)) {
$image = fread($fp, filesize($img));
fclose($fp);
$base64 = chunk_split(base64_encode($image));
// 输出
$encode = 'data:image/jpg/png/gif;base64,' . $base64;
echo $encode;
}
}
private function __clone()
{
}
}
$img_path = ImgToBase64::getInstance()->getClientArgs();
ImgToBase64::getInstance()->imgToBase64($img_path);