PHP 图片压缩至指定尺寸 封装函数

/**
 * @param $img 图片地址
 * @param string $width 宽
 * @param string $height 高
 * @param string $ratio 保持原比例
 * @return string 生成的地址
 */
public function resize_fuc($img, $width, $height, $ratio)
{

	$info = get_img_info($img);
	$name = pathinfo($img)['filename'];
	$dirname = pathinfo($img)['dirname'];
	$ext = pathinfo($img)['extension'];

	$im = NULL;
	$type = strtolower($info['type']);

	if (!in_array($type, ['jpg', 'jpeg', 'gif', 'png'])) {
		return FALSE;
	}
	$type = ($type == 'jpg' ? 'jpeg' : $type);

	$scale = $info['width'] / $info['height'];

	if ($ratio == TRUE) {
		$forScale = $width / $height;
		$x = 0;
		$y = 0;
		if ($scale >= $forScale) {
			$width = (int)($height * $scale);
			$rate = $info['height']/$height;
		} else {
			$height = (int)($width / $scale);
			$rate = $info['width']/$width;
		}
	} else {
		$forScale = $width / $height;
		if ($scale >= $forScale) {
			$x = ($info['width'] - $info['height'] * $forScale) / 2;
			$y = 0;
			$rate = $info['height'] / $height;
		} else {
			$x = 0;
			$y = ($info['height'] - $info['width'] / $forScale) / 2;
			$rate = $info['width'] / $width;
		}
	}

	if($width>$info['width'] || $height>$info['height']){
		return;
	}


	$imageCreateFun = 'imagecreatefrom' . $type;
	$im = $imageCreateFun($img);
	$thumb = $dirname . '/' . $name . '_tmp' . "." . $ext;

	$imageFun = 'image' . $type;
	$imageFun($im, $thumb);

	$thumbNew = imagecreatetruecolor($width, $height);

	imagecopyresampled(
		$thumbNew, $im,
		0, 0, intval($x), intval($y),
		intval($width * 1), intval($height * 1), intval($width * $rate), intval($height * $rate)
	);

	$imageFun($thumbNew, $thumb);

	imagedestroy($im);
	imagedestroy($thumbNew);

	rename($thumb,$img);
	return $img;
}
function get_img_info($img) {
    if(!is_file($img) || !in_array(strtolower(pathinfo($img)['extension']),['jpg','jpeg','bmp','gif','png'])){
        return false;
    }
    $img_info = getimagesize($img);
    if ($img_info !== false) {
        $img_type = strtolower(substr(image_type_to_extension($img_info[2]), 1));
        $info = array("width" => $img_info[0], "height" => $img_info[1], "type" => $img_type, "mime" => $img_info['mime'], );
        return $info;
    } else {
        return false;
    }
}

LNMP.org 一键安装包 安装 redis

LNMP 1.2缓存加速类扩展(xcache/Redis/memcached/eAccelerator)、imageMagick、ionCube安装教程

https://lnmp.org/faq/addons.html
cd ~
wget http://soft.vpser.net/lnmp/lnmp1.5.tar.gz -cO lnmp1.5.tar.gz && tar zxf lnmp1.5.tar.gz && cd lnmp1.5
./addons.sh install redis 

配置文件 

vim /usr/local/redis/etc/redis.conf

修改 

protected-mode no //protected-mode 参数是为了禁止外网访问 redis,酌情使用
daemonize yes 

运行

/usr/local/redis/bin/redis-server /usr/local/redis/etc/redis.conf

查看 redis 运行状态

systemctl status redis.service

卸载 

./addons.sh uninstall redis

ThinkPHP 5 引入 百度云 BaiduBCE SDK

项目根目录使用 Composer

composer require baidubce/bce-sdk-php

在 Controller 中引入

<?php
require '../vendor/autoload.php';//这句不用,自动引入
use BaiduBce\Services\Bos\BosClient;

测试连接

public function baidu(){
  $BOS_TEST_CONFIG =
	array(
	  'credentials' => array(
	  'accessKeyId' => '684b94f7675142d79ed2bxxxxxxxxxxx',
	  'secretAccessKey' => '0ee6b11cc38445fc8xxxxxxxxxxxxx',
	  ),
	  'endpoint' => 'https://todo.cdn.bcebos.com',
	);
  $client = new BosClient($BOS_TEST_CONFIG);
  dump($client);
}

输出结果

上传文件测试

public function baidu(){
  $BOS_TEST_CONFIG =
    array(
      'credentials' => array(
      'accessKeyId' => '684b94f7675142d79ed2bxxxxxxxxxxx',
      'secretAccessKey' => '0ee6b11cc38445fc8xxxxxxxxxxxxx',
      'sessionToken' => ''
      ),
    'endpoint' => 'https://todo.cdn.bcebos.com',
    'stsEndpoint' => '',
  );
  $client = new BosClient($BOS_TEST_CONFIG);
  $bucketName = 'path';
  $a = $client->putObjectFromFile($bucketName, 'abc.png', 'tmp/x.png');
  dump($a);
}

如果用的是百度的服务器,可能出现在线报错

[curl] 6: Could not resolve host: todo.cdn.bcebos.com; Unknown error [url] 

DNS 的问题

vim /etc/resolv.conf 

修改

但是修改 DNS 的方式会使无法使用内网传输,

所以需要将上传地址改为官方域名,不要用 CDN 加速域名,这样百度内网服务器之间网就可以妙传了

将之前的项目图片进行了压缩

图片多了太占空间,之前项目的图片有 10G,删掉可以留着占空间,近期就写了个图片压缩的程序 压缩 JPG/JPEG/BMP/PNG/GIF,将文件夹里的文件扫描添加至队列,然后执行计划任务将六万多张图片压缩完成。

仅部分图片由于本身格式存在问题无法压缩成功。

原本不压缩尺寸只压缩格式,发现还是需要占3个多G,后将宽度大于400的压缩至400,减少至不到2G

试了用下腾讯的智图PC客户端

操作逻辑感人

1 无法识别文件夹

2 正在压缩时添加新文件会替换掉现在的压缩列队

3 开启裁剪缩放默认为 1*1,手动修改为自己的设定如 400*400,退出软件在再进入会变成 1*1,且裁剪缩放为开启。如果你选择了替换原图,那么恭喜你了

4 文件过多会超级慢,一个五万文件的文件夹(含子目录),扫描有将近一个小时(就算用 PHP 操作也不会超过 30s),扫描完成后默认先压缩文件夹……然后提示你文件类型出错,而且你的界面会很卡,想看下滚动条都难

5 安装过程不会自动判断是否需要安装额外的库,如果你没有选中且本机原先没有,那么它会一直安装失败

6 有时会卡住。文件普普通通但就是不压缩

先写这么多

CentOS 6 无法安装 Swoole 提示 GCC 4.8 or later required

自行编译安装 gcc,依然提示,

当使用 gcc -v 提示已安装 gcc version 4.8.2

但使用 yum install gcc 提示是 4.4 且为最新版本

解决办法,卸载 yum 版 gcc,然后重新编译安装

yum remove gcc

CentOS 6 升级安装gcc 4.8

https://blog.csdn.net/bdss58/article/details/78175892

1. 导入CERN’s GPG key

rpm --import http://linuxsoft.cern.ch/cern/slc68/x86_64/RPM-GPG-KEY-cern

2. 添加slc6-devtoolset yum源

wget -O /etc/yum.repos.d/slc6-devtoolset.repo http://linuxsoft.cern.ch/cern/devtoolset/slc6-devtoolset.repo

3. 安装devtoolset-2

yum install devtoolset-2

4. 生效devtoolset-2

source /opt/rh/devtoolset-2/enable

可以将此命令写入.bashrc中,以免每次手动执行

echo 'source /opt/rh/devtoolset-2/enable' >> ~/.bashrc

验证一下gcc版本:

$ gcc --version
gcc (GCC) 4.8.2 20140120 (Red Hat 4.8.2-15)
...

CentOS7 GIF 压缩 Gifsicle 安装

Gifsicle 官网

https://www.lcdf.org/gifsicle/
cd ~
wget https://www.lcdf.org/gifsicle/gifsicle-1.91.tar.gz 
tar -zxvf gifsicle-1.91.tar.gz
cd gifsicle-1.91/
./configure 
make 
make install

使用:

gifsicle -O3 path.gif -o newpath.gif
[root@instance-jewlel2q tmp]# gifsicle --sinfo x.gif
* x.gif 98 images
  logical screen 800x450
  global color table [256]
  background 0
  loop forever
  + image #0 800x450
    compressed size 133044
    comment Edited with ezgif.com online GIF maker
    disposal asis delay 0.10s
  + image #1 800x450
    compressed size 133243
    local color table [256]
    disposal asis delay 0.10s
  + image #2 800x450
    compressed size 134192
    local color table [256]
    disposal asis delay 0.10s
  + image #3 800x450
    compressed size 130221
    local color table [256]
    disposal asis delay 0.10s
[root@instance-jewlel2q tmp]# gifsicle -O3 x.gif -o x1.gif --resize-fit 400
gifsicle: invalid dimensions ‘400’ (want WxH)
gifsicle: warning: too many colors, using local colormaps
  (You may want to try ‘--colors 256’.)
[root@instance-jewlel2q tmp]# gifsicle -h
'Gifsicle' manipulates GIF images. Its most common uses include combining
single images into animations, adding transparency, optimizing animations for
space, and printing information about GIFs.

Usage: gifsicle [OPTION | FILE | FRAME]...

Mode options: at most one, before any filenames.
  -m, --merge                   Merge mode: combine inputs, write stdout.
  -b, --batch                   Batch mode: modify inputs, write back to
                                same filenames.
  -e, --explode                 Explode mode: write N files for each input,
                                one per frame, to 'input.frame-number'.
  -E, --explode-by-name         Explode mode, but write 'input.name'.

General options: Also --no-OPTION for info and verbose.
  -I, --info                    Print info about input GIFs. Two -I's means
                                normal output is not suppressed.
      --color-info, --cinfo     --info plus colormap details.
      --extension-info, --xinfo --info plus extension details.
      --size-info, --sinfo      --info plus compression information.
  -V, --verbose                 Prints progress information.
  -h, --help                    Print this message and exit.
      --version                 Print version number and exit.
  -o, --output FILE             Write output to FILE.
  -w, --no-warnings             Don't report warnings.
      --no-ignore-errors        Quit on very erroneous input GIFs.
      --conserve-memory         Conserve memory at the expense of speed.
      --multifile               Support concatenated GIF files.

Frame selections:               #num, #num1-num2, #num1-, #name

Frame change options:
  --delete FRAMES               Delete FRAMES from input.
  --insert-before FRAME GIFS    Insert GIFS before FRAMES in input.
  --append GIFS                 Append GIFS to input.
  --replace FRAMES GIFS         Replace FRAMES with GIFS in input.
  --done                        Done with frame changes.

Image options: Also --no-OPTION and --same-OPTION.
  -B, --background COL          Make COL the background color.
      --crop X,Y+WxH, --crop X,Y-X2,Y2
                                Crop the image.
      --crop-transparency       Crop transparent borders off the image.
      --flip-horizontal, --flip-vertical
                                Flip the image.
  -i, --interlace               Turn on interlacing.
  -S, --logical-screen WxH      Set logical screen to WxH.
  -p, --position X,Y            Set frame position to (X,Y).
      --rotate-90, --rotate-180, --rotate-270, --no-rotate
                                Rotate the image.
  -t, --transparent COL         Make COL transparent.

Extension options:
      --app-extension N D       Add an app extension named N with data D.
  -c, --comment TEXT            Add a comment before the next frame.
      --extension N D           Add an extension number N with data D.
  -n, --name TEXT               Set next frame's name.
      --no-comments, --no-names, --no-extensions
                                Remove comments (names, extensions) from input.
Animation options: Also --no-OPTION and --same-OPTION.
  -d, --delay TIME              Set frame delay to TIME (in 1/100sec).
  -D, --disposal METHOD         Set frame disposal to METHOD.
  -l, --loopcount[=N]           Set loop extension to N (default forever).
  -O, --optimize[=LEVEL]        Optimize output GIFs.
  -U, --unoptimize              Unoptimize input GIFs.
  -j, --threads[=THREADS]       Use multiple threads to improve speed.

Whole-GIF options: Also --no-OPTION.
      --careful                 Write larger GIFs that avoid bugs in other
                                programs.
      --change-color COL1 COL2  Change COL1 to COL2 throughout.
  -k, --colors N                Reduce the number of colors to N.
      --color-method METHOD     Set method for choosing reduced colors.
  -f, --dither                  Dither image after changing colormap.
      --gamma G                 Set gamma for color reduction [2.2].
      --resize WxH              Resize the output GIF to WxH.
      --resize-width W          Resize to width W and proportional height.
      --resize-height H         Resize to height H and proportional width.
      --resize-fit WxH          Resize if necessary to fit within WxH.
      --scale XFACTOR[xYFACTOR] Scale the output GIF by XFACTORxYFACTOR.
      --resize-method METHOD    Set resizing method.
      --resize-colors N         Resize can add new colors up to N.
      --transform-colormap CMD  Transform each output colormap by shell CMD.
      --use-colormap CMAP       Set output GIF's colormap to CMAP, which can
                                be 'web', 'gray', 'bw', or a GIF file.

Report bugs to <ekohler@gmail.com>.
Too much information? Try 'gifsicle --help | more'.