PHP实现图片文件伪加密打乱简单思路
在PHP开发中偶尔有些特殊情况不希望直接暴露某些图片的真实地址,除了可以给图片存入数据库、图片写入其他格式的文件再读取显示之外,这里写了个简单的将图片字节前后颠倒打乱的方法,class SevStudioImg{
function pr($length,$length0,$length1){
echo <<
length:{$length}
length0:{$length0}
length1:{$length1}
SS;
exit;
}
//图片打乱
function fix($path){
$hd = fopen($path,'r');
if($hd === False){
return null;
}
$length = filesize($path);
$step = $length % 2 == 0 ? $length / 2 : (($length + 1) / 2);
$data[] = fread($hd,$step);
$data[] = fread($hd,$length - $step);
fclose($hd);
return $data[1].$data[0];
}
//图片复原
function read($path){
$hd = fopen($path,'r');
if($hd === False){
return null;
}
$length = filesize($path);
$step = $length % 2 == 0 ? $length / 2 : (($length - 1) / 2);
$data[] = fread($hd,$step);
$data[] = fread($hd,$length - $step);
fclose($hd);
return $data[1].$data[0];
}
//将图片数据保存为图片
function save($data,$path){
$writer = fopen($path,'w');
fwrite($writer,$data);
fclose($writer);
}
//将图片数据输出到浏览器,显示图片
function show($data){
header('Content-Type:image/jpeg');
echo $data;
}
}
用的时候先做类的实例化$hp = new SevStudioImg();
打乱图片$data = $hp->fix('原图路径');
$hp->save($data,'新图保存路径');
显示方法$data = $hp->read('打乱后图片的路径');
$hp->show($data);//直接输出图片到浏览器
$hp->save($data,'还原后图片保存路径');