thinkphp6: 用imagemagick库生成缩略图(ImageMagick 6.9.11-60 / php 8.1.1 / thinkphp v6.0.10LTS )


一,安装ImageMagick库:

1,apt-get安装
root@lhdpc:~# apt-get install imagemagick
2,查看版本:
root@lhdpc:~# convert --version
Version: ImageMagick 6.9.11-60 Q16 x86_64 2021-01-25 https://imagemagick.org
Copyright: (C) 1999-2021 ImageMagick Studio LLC
License: https://imagemagick.org/script/license.php
Features: Cipher DPC Modules OpenMP(4.5)
Delegates (built-in): bzlib djvu fftw fontconfig freetype heic jbig jng jp2 jpeg lcms lqr ltdl lzma openexr pangocairo png tiff webp wmf x xml zlib

可以看到版本是6.9.11

3,查看命令的路径:
root@lhdpc:~# whereis convert
convert: /usr/bin/convert /usr/share/man/man1/convert.1.gz

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/
         或: https://gitee.com/liuhongdi

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,编写js代码

Upload.vue
<template>
<div>
  请选择上传幻灯图片:
  <input type="file" id="back" ref="backfile" multiple  @change="handleFile" />
  <div id="imglist" style="width:100%;">
    <div v-for="(item,i) in selFiles" :key="i" style="float:left;margin-left: 20px;margin-top: 20px;height:150px;position:relative;">
      <img :src="item.fileimg"  style="height:150px;"/>
      <div @click="delqueue(i)" style="position:absolute;width:30px;height:30px;line-height:30px;border-radius:15px;top:-15px;right:-15px;background:#ff0000;">xdiv>
    div>
  div>
  <input type="button" value="上传" @click="upload" />
div>
template>
 
<script>
import {ref} from "vue"
import { apiUpload} from '@/api/api';
import {ElMessage} from "element-plus";
export default {
  name: "Upload",
  setup() {
    //选中的图片文件,保存在数组中
    const selFiles = ref([]);
    //选中图片后的处理
    const handleFile = () => {
      let filePaths = window.event.target.files;
      //清空原有缩略图
      if (filePaths.length === 0) {
        //未选择,则返回
        return
      } else {
        //清空数组中原有图片
        selFiles.value.length = 0;
      }
      //把新选中的图片加入数组
      for( var i=0;i<filePaths.length; i++ ){
        let file = filePaths[i];
        let one = {
          fileimg:URL.createObjectURL(file),  //预览用
          file:file,
        }
        selFiles.value.push(one);
      }
    }
    //从上传数组中删除
    const delqueue = (index) => {
      if (confirm("确定从上传队列中删除当前图片?")) {
        selFiles.value.splice(index,1);
      }
    }
    //上传
    const upload = () => {
      //判断是否选中文件
      var file = selFiles.value[0].file;
      if (typeof(file) === "undefined") {
        alert("请在上传前先选中文件!");
        return;
      }
      // 创建一个表单数据
      var data = new FormData();
 
      //遍历文件,添加到form
      for( var i=0;i<selFiles.value.length; i++ ){
        let fileOne = selFiles.value[i].file;
        console.log("上传:"+fileOne.name)
        data.append("file[]",fileOne);
      }
      //上传
      apiUpload(data).then(res => {
        //成功
        if (res.code == 0) {
          //提示
          ElMessage.success("上传成功!");
        } else {
          ElMessage.error("上传失败:"+res.msg);
        }
      }).catch((error) => {
        console.log(error)
      })
    }
    return {
      handleFile,
      selFiles,
      delqueue,
      upload,
    }
  }
}
script>
 
<style scoped>
 
style>
三,编写php代码: 1,lib/util/imageModify.php
<?php
namespace app\lib\util;
 
class imageModify {
 
    private $ImageMagickDIR = "/usr/bin";
 
    //按指定长边生成缩略图
    function resizeImageByLongSide($origImage,$destImage,$size)
    {
        $cmdtmb=$this->ImageMagickDIR."/convert -size ".$size."x".$size.
            " -resize ".$size."x".$size." +profile '*' ".$origImage." ".$destImage." 2>&1";
        $rettmb=shell_exec($cmdtmb);
        return $rettmb;
    }
}
2,controller/Article.php
    /**
     * 保存上传的多个文件
     *
     * @return \think\Response
     */
    public function savemulti() {
        $files = request()->file('file');
        if ($files === null) {
            $files = [];
        }
        $savename = [];
        foreach($files as $file){
            $baseDir = GConfig::get('images.goodsImageDir');
            $origDir = "orig";
            $dir = $baseDir."/".$origDir;
            if (!is_dir($dir)) {
                mkdir($dir);
            }
 
            $tmbDir = "tmb";
            $tdir = $baseDir."/".$tmbDir;
            if (!is_dir($tdir)) {
                mkdir($tdir);
            }
 
            $filename = uniqid();
            $destFile = $dir."/".$filename.".".$file->getOriginalExtension();
            $destTmb = $tdir."/".$filename.".".$file->getOriginalExtension();
            $isUpload = move_uploaded_file($file->getPathname(),$destFile);
            if ($isUpload) {
                $savename[] = $origDir."/".$filename.".".$file->getOriginalExtension();
                //从保存下来的文件,生成缩略图
                $im = new imageModify();
                $im->resizeImageByLongSide($destFile,$destTmb,500);
            }
        }
        return  Result::Success($savename);
    }

四,测试效果

1,访问: 选择文件上传:如图: 2,上传后效果: 3,查看tmb文件的长宽:

五,查看php和thinkphp的版本:

php:
liuhongdi@lhdpc:/data/php/admapi$ php --version
PHP 8.1.1 (cli) (built: Dec 20 2021 16:12:16) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.1, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.1, Copyright (c), by Zend Technologies 
thinkphp:
liuhongdi@lhdpc:/var/www/html$ cd /data/php/admapi/
liuhongdi@lhdpc:/data/php/admapi$ php think version
v6.0.10LTS