<?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;
}

posted on 2014-02-22 12:50  老游条  阅读(288)  评论(0编辑  收藏  举报