找出html中的图片、包括css中的图片,读出图片数据转换为base64数据
2024-10-20 16:25:48
<?php
echo ">> 图片的地址,css里面的要打单引号\r\n";
echo ">> 相同的图片,使用css实现图片地址只出现一次,有助于减小文件体积\r\n";
echo ">> 因为凡是出现图片地址的地方,都会被转换成base64字符串\r\n";
$dirs = scandir('./');
if(count($dirs)<3) die('bad dir');// echo $_dir.' is empty!'.chr(10);
//else echo $_dir.' = '.count($dirs).chr(10);
foreach($dirs as $dir){
if($dir=='.'||$dir=='..') continue;
$dir= './'.$dir;
$ext=substr($dir, -4);
if($ext == 'html'){
g($dir);
}
}
function g($f){
$data = file_get_contents($f);
preg_match_all("/([\"'])([^\"'\n]+\.(gif|jpg|png))\\1/", $data, $out);
for($i=0;$i<count($out[1]);$i++){
echo ' **> found img: '.$out[0][$i]."\r\n";
$str = img2str($out[2][$i]);
$l1 = substr($out[0][$i],0,1);
if($l1!='\''&&$l1!='"')
$l1 = "'";
$data = str_replace($out[0][$i],$l1.$str.$l1,$data);
} $data = str_replace("\\","\\\\", $data);
$data = str_replace("\"","\\\"", $data);
$data = str_replace("\r\n","\\n", $data); $f = str_replace('html','txt',$f);
file_put_contents($f,$data);
echo '*> '.$f.' OK
';
}
$img_cache=array();
function img2str($file){
global $img_cache;
if(isset($img_cache[$file])) return $img_cache[$file];
$data = file_get_contents($file);
$file = 'tmp_'.basename($file);
file_put_contents($file, $data);
$type=getimagesize($file);//取得图片的大小,类型等
$fp=fopen($file,"r")or die("Can't open file");
$file_content=base64_encode(fread($fp,filesize($file)));//base64编码
switch($type[2]){//判读图片类型
case 1:$img_type="gif";break;
case 2:$img_type="jpg";break;
case 3:$img_type="png";break;
}
$img='data:image/'.$img_type.';base64,'.$file_content;//合成图片的base64编码
fclose($fp);
$img_cache[$file] = $img;
return $img;
}
最新文章
- 理解数据库的PDO处理的理念
- c语言强制类型转换
- Less小记
- jQuery扩展与noConflict的用法-小示例
- Linux下MySQL安装和配置
- PS 图像调整算法——亮度调整
- What Are You Talking About (map)
- Android 开发版本统一
- A股、B股区别
- Linux基础命令---文本统计paste
- 贪吃蛇Ground Java实现(二)
- Nginx HTTPS功能部署实践
- springmvc与ajax交互常见问题
- 大数据开发实战:Storm流计算开发
- day07(Set接口,HashSet类,hashcoad(),Collections工具类,Map集合)
- git 代码分支合并merge提交新修改远程以及本地分支
- Effective STL 43: Prefer algorithm calls to hand-written loops
- java定时器学习
- (转)Java 中关于String的空对象(null) ,空值(empty),空格
- hadoop 的job.setOutputKeyClass和job.setOutputValueClass的几个问题