search
HomeBackend DevelopmentPHP TutorialCommon image processing methods encapsulated by CI framework (thumbnails, watermarks, rotation, upload, etc.)_php example

The examples in this article describe common image processing methods encapsulated by the CI framework. Share it with everyone for your reference, the details are as follows:

In fact, when uploading pictures on the WeChat mobile phone, it is best to use thumbnails for the list pictures to save data traffic. No, it was tricked by mobile phones again. It stopped after one point of phone bill sign, and it stopped when the traffic amount was 90 yuan. I was also drunk. . . .

No more nonsense, the following is written using CI's built-in image processing library. I'm not talented, so please point out any omissions. Thank you.

/**
* 生成缩略图
* @param  $path 原图的本地路径
* @return null 创建一个 原图_thumb.扩展名 的文件
*
*/
public function dealthumb($path){
    $config['image_library'] = 'gd2';
    $config['source_image'] = $path;
    $config['create_thumb'] = TRUE;
    //生成的缩略图将在保持纵横比例 在宽度和高度上接近所设定的width和height
    $config['maintain_ratio'] = TRUE;
    $config['width'] = 80;
    $config['height'] = 80;
    $this->load->library('image_lib', $config);
    $this->image_lib->resize();
    $this->image_lib->clear();
}
/*
* 处理图像旋转
*/
public function transroate($path,$imgpath){
    $this->load->library('image_lib');
    //(必须)设置图像库
    $config['image_library'] = 'gd2';
    $newname = time().'_rote.jpg';
    //设置图像的目标名/路径
    $config['new_image'] =$imgpath.$newname;
    //(必须)设置原始图像的名字/路径
    $config['source_image'] = $path;
    //决定新图像的生成是要写入硬盘还是动态的存在
    $config['dynamic_output'] = FALSE;
    //设置图像的品质。品质越高,图像文件越大
    $config['quality'] = '90%';
    //有5个旋转选项 逆时针90 180 270 度 vrt 竖向翻转 hor 横向翻转
    $config['rotation_angle'] = 'vrt';
    $this->image_lib->initialize($config);
    if(@$this->image_lib->rotate()){
      $this->image_lib->clear();
      return $config['new_image'];
    }else{
      $this->image_lib->clear();
      return '';
    }
}
/**
* 处理图像水印
*/
public function overlay($path,$imgpath){
    $this->load->library('image_lib');
    $newname = time().'_over.jpg';
    //设置新图像名称
    $config['new_image'] =$imgpath.$newname;
    //调用php gd库 绘图
    $config['image_library'] = 'gd2';
    //源图像 本地地址
    $config['source_image'] = $path;
    //覆盖文字
    $config['wm_text'] = 'Copyright 2015 - Friker';
    //覆盖类型 文字/图像
    $config['wm_type'] = 'text';
    //文字字体类型
    //$config['wm_font_path'] = 'C:\Windows\Fonts\vrinda.ttf';
    //字体大小
    $config['wm_font_size'] = '16';
    //字体颜色
    $config['wm_font_color'] = 'ff0000';
    //垂直方向距离顶端距离
    $config['wm_vrt_alignment'] = '20';
    //水平方向距离左端距离
    $config['wm_hor_alignment'] = 'center';
    //padding
    $config['wm_padding'] = '20';
    $this->image_lib->initialize($config);
    if($this->image_lib->watermark()){
      $this->image_lib->clear();
      return $config['new_image'];
    }else{
      $this->image_lib->clear();
      return '';
    }
}
/**
*  处理图片上传
*  文件上传类 通过前台 上传文件
*/
public function uploadfile(){
    //文件上传部分
    // 处理文件
    // $data = '';
    $this->load->helper('url');
    $formpic = key($_FILES);
    //文件处理部分
    if(false === empty($_FILES[$formpic]['tmp_name'])){
      //设置文件上传的路径
      $upload['upload_path'] = "./public/img/";
      //限制文件上传的类型
      $upload['allowed_types'] = 'jpeg|jpg|gif|png';
      //限制文件上传的大小
      $upload['max_size'] = 2048;
      //设置文件上传的路径
      $upload['file_name'] = date('YmdHis', time()).rand(10000, 99999);
      //加载文件上传配置信息
      $this->load->library('upload', $upload);
      //处理文件上传
      $this->upload->do_upload($formpic);
      //返回文件上传信息
      $image = $this->upload->data();
      /*
       'file_name' => string '2015071702051718388.jpg' (length=23)
       'file_type' => string 'image/jpeg' (length=10)
       'file_path' => string 'E:/wamp/www/testci/public/img/' (length=30)
       'full_path' => string 'E:/wamp/www/testci/public/img/2015071702051718388.jpg' (length=53)
       'raw_name' => string '2015071702051718388' (length=19)
       'orig_name' => string '2015071702051718388.jpg' (length=23)
       'client_name' => string 'u=415761610,1548338330&fm=116&gp=0.jpg' (length=38)
       'file_ext' => string '.jpg' (length=4)
       'file_size' => float 3.74
       'is_image' => boolean true
       'image_width' => int 146
       'image_height' => int 220
       'image_type' => string 'jpeg' (length=4)
       'image_size_str' => string 'width="146" height="220"' (length=24)
       */
      //var_dump($image);
      //返回文件上传名字
      $data = $image['file_name'];
      $this->dealthumb($image['full_path']);
      $this->overlay($image['full_path'],$image['file_path']);
      $this->transroate($image['full_path'],$image['file_path']);//
      $thumbdata = '';
      //生成缩略图名称
      $pos = strripos($image['file_name'], ".");
      $newname = substr($image['file_name'], 0,$pos)."_thumb".substr($image['file_name'], $pos);
      if(file_exists($image['file_path'].$newname)){
        $thumbdata = $newname;
      }
    }
    //$dirroot = $_SERVER['DOCUMENT_ROOT'];
    //$this->dealthumb($dirroot."/public/img/".$data);
    //上传失败
    if(!$data){
      echo json_encode(array('status'=>0,'msg'=>"上传失败!"));
    }else{
    //上传成功
      echo json_encode(array(
        'name'=>$data,
        'pic'=>base_url()."public/img/".$data,
        'picthumb'=>$thumbdata == '' ?$data:$thumbdata
        ));
    }
}

The following is the basic html code of the front end:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="/public/stylesheets/bootstrap.min.css" />
<link rel="stylesheet" href="/public/stylesheets/bootstrap-responsive.min.css" />
<link rel="stylesheet" href="/public/stylesheets/matrix-style.css" />
<link rel="stylesheet" href="/public/stylesheets/matrix-media.css" />
<script type="text/javascript" src="/public/javascripts/jquery.min.js"></script>
<script type="text/javascript" src="/public/javascripts/jquery.form.js"></script>
<script type="text/javascript" src="/public/javascripts/jquery.validate.js"></script>
<style type="text/css">
body{background:#eeeeee; margin:0px;}
</style>
</head>
<body>
<div class="control-group">
  <label class="control-label"> 分享logo: </label>
  <div class="controls">
     <input type="file" name="sharepic" id="sharepic"/>
     <input type="hidden" name="act_sharepic" value="" id="act_sharepic"/>(<sapn class="fred">最佳大小为 80 X 80 像素</sapn>)
     <p style="margin:20px 0;"><img src="/static/imghwm/default1.png"  data-src="/public/img/default.png"  class="lazy" alt="" id="sharepic_img"></p>
  </div>
</div>
<script type="text/javascript">
$(function () {
  /*****************图片上传部分开始 *******************/
  var act = "<form class='myupload' action='"+"<&#63;php echo site_url('mytest/uploadfile');&#63;>"+"' method='post' enctype='multipart/form-data'></form>";
  $("#sharepic").change(function(){
    $(this).wrap(act);
    $(this).parent(".myupload").ajaxSubmit({
      dataType: 'json',
      success: function(data) {
        var src = data.pic;
        //更改预览图像地址
        $('#sharepic_img').attr("src",src);
        $('#act_sharepic').val(data.name);
        $('#sharepic').unwrap();
      },
      error:function(xhr){
        alert(JSON.parse(xhr));
      }
    });
  });
})
</script>
</body>
</html>

Readers who are interested in more CodeIgniter related content can check out the special topics of this site: "codeigniter introductory tutorial", "CI (CodeIgniter) framework advanced tutorial", "php excellent development framework summary", "ThinkPHP introductory tutorial", "ThinkPHP Summary of common methods", "Zend FrameWork framework introductory tutorial", "php object-oriented programming introductory tutorial", "php+mysql database operation introductory tutorial" and "php common database operation skills summary"

I hope this article will be helpful to everyone’s PHP program design based on the CodeIgniter framework.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools