结合数据库,删除项目多余图片,并使用tp5压缩图片
// 结合数据库,删除项目多余图片,并压缩图片
/*********************** ① 和 ②不建议同时使用,可能会崩溃 ***************************/
public function editimg(){
ini_set('max_execution_time',0);
ini_set('memory_limit','256M'); //升级为256M内存
$errors = null;
//① 表commonweal里处理图片
$pic1 = Db::table('commonweal')->where('picture <> ""')->column('picture');
$pic2 = Db::table('commonweal')->where('street_picture <> ""')->column('street_picture');
$pic3 = Db::table('commonweal')->where('community_picture <> ""')->column('community_picture');
$pics = array_merge_recursive($pic1, $pic2, $pic3);
foreach ($pics as $pic) {
$dir = '/static/admin/uploads/' . $pic;
$dir2 = '/static/admin/uploads/product/' . $pic;
if(file_exists('.'.$dir)) {
$file = $dir;
}
if(file_exists('.'.$dir2)) {
$file = $dir2;
}
//有重复的跳过
if(file_exists('./aaa'.$file)) {
continue;
}
if(!is_dir(dirname('./aaa'.$file))){
mkdir(dirname('./aaa'.$file), 0644, true);
}
if(!copy('.'.$file, './aaa'.$file)){
$errors[] = $file;
}
// @TODO 验证图片是否损坏
//压缩图片
$thumb = './aaa'.$file;
list($width, $height) = getimagesize($thumb);
$max = max($width, $height);
if($max > 1280){
$image = \think\Image::open($thumb);
//按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
if($width > $height){
$image->thumb(1280, 720)->save($thumb);
}else{
$image->thumb(720, 1280)->save($thumb);
}
}
}
//② 表project里处理图片
$pic1 = Db::table('project')->where('content like "%<img %"')->column('content');
$pics = [];
$reg = '/<img (.*?)+src=[\'"](.*?)[\'"]/i';
foreach ($pic1 as $pic){
preg_match_all( $reg , $pic , $result );
$pics = array_merge_recursive($pics, $result[2]);
}
array_walk($pics, function (&$v, $k, $pics){
$v = strstr($v, '/static/admin');
}, $pics);
// 获取去掉重复数据的数组
/*$unique_arr = array_unique ( $pics );
// 获取重复数据的数组
$repeat_arr = array_diff_assoc ( $pics, $unique_arr );*/
// print_r(json_encode($pics));
// exit;
foreach ($pics as $pic) {
if(file_exists('.' . $pic) && !empty($pic)) {
$thumb = './aaa' . $pic;
if (file_exists($thumb)) {
continue;
}
if (!is_dir(dirname($thumb))) {
mkdir(dirname($thumb), 0644, true);
}
if (!copy('.' . $pic, $thumb)) {
$errors[] = $pic;
}
//压缩图片
list($width, $height, $type) = getimagesize($thumb);
//检测图片是否损坏
$fun = 'imagecreatefrom' . image_type_to_extension($type, false);
if(@$fun($thumb) === false){
echo $pic . '<br>';continue;
}
$max = max($width, $height);
if ($max > 1280) {
$image = \think\Image::open($thumb);
//按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
if ($width > $height) {
$image->thumb(1280, 720)->save($thumb);
} else {
$image->thumb(720, 1280)->save($thumb);
}
}
}
}
dump($errors);
dump($pics);
exit;
}
注:代码由本人编写,如有问题可以联系本人,谢谢。