Home Backend Development PHP Tutorial About CI framework encapsulation of commonly used image processing methods

About CI framework encapsulation of commonly used image processing methods

Jun 14, 2018 pm 01:45 PM
ci framework Image Processing encapsulation

This article mainly introduces the common image processing methods encapsulated by the CI framework, involving thumbnails, watermarks, rotation, uploading and other operations for images. Friends in need can refer to the following

The examples of this article describe CI Frame encapsulation of common image processing methods. I share it with you for your reference. The details are as follows:

In fact, when uploading pictures on WeChat mobile phone, it is best to use thumbnails for the list pictures to save traffic. No, this is another scam by mobile phones. The phone bill is 1 point. It was shut down, and the traffic was 90 yuan before it was shut down. I was also drunk. . .

Let’s not talk nonsense. The following is written using CI’s built-in image processing library. I am 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
        ));
    }
}
Copy after login

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>
<p class="control-group">
  <label class="control-label"> 分享logo: </label>
  <p 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="/public/img/default.png" alt="" id="sharepic_img"></p>
  </p>
</p>
<script type="text/javascript">
$(function () {
  /*****************图片上传部分开始 *******************/
  var act = "<form class=&#39;myupload&#39; action=&#39;"+"<?php echo site_url(&#39;mytest/uploadfile&#39;);?>"+"&#39; method=&#39;post&#39; enctype=&#39;multipart/form-data&#39;></form>";
  $("#sharepic").change(function(){
    $(this).wrap(act);
    $(this).parent(".myupload").ajaxSubmit({
      dataType: &#39;json&#39;,
      success: function(data) {
        var src = data.pic;
        //更改预览图像地址
        $(&#39;#sharepic_img&#39;).attr("src",src);
        $(&#39;#act_sharepic&#39;).val(data.name);
        $(&#39;#sharepic&#39;).unwrap();
      },
      error:function(xhr){
        alert(JSON.parse(xhr));
      }
    });
  });
})
</script>
</body>
</html>
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

About the method of loading views in the CI framework view

About the CI framework extension system core class Method analysis

The above is the detailed content of About CI framework encapsulation of commonly used image processing methods. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How is Wasserstein distance used in image processing tasks? How is Wasserstein distance used in image processing tasks? Jan 23, 2024 am 10:39 AM

Wasserstein distance, also known as EarthMover's Distance (EMD), is a metric used to measure the difference between two probability distributions. Compared with traditional KL divergence or JS divergence, Wasserstein distance takes into account the structural information between distributions and therefore exhibits better performance in many image processing tasks. By calculating the minimum transportation cost between two distributions, Wasserstein distance is able to measure the minimum amount of work required to transform one distribution into another. This metric is able to capture the geometric differences between distributions, thereby playing an important role in tasks such as image generation and style transfer. Therefore, the Wasserstein distance becomes the concept

In-depth analysis of the working principles and characteristics of the Vision Transformer (VIT) model In-depth analysis of the working principles and characteristics of the Vision Transformer (VIT) model Jan 23, 2024 am 08:30 AM

VisionTransformer (VIT) is a Transformer-based image classification model proposed by Google. Different from traditional CNN models, VIT represents images as sequences and learns the image structure by predicting the class label of the image. To achieve this, VIT divides the input image into multiple patches and concatenates the pixels in each patch through channels and then performs linear projection to achieve the desired input dimensions. Finally, each patch is flattened into a single vector, forming the input sequence. Through Transformer's self-attention mechanism, VIT is able to capture the relationship between different patches and perform effective feature extraction and classification prediction. This serialized image representation is

How to use AI technology to restore old photos (with examples and code analysis) How to use AI technology to restore old photos (with examples and code analysis) Jan 24, 2024 pm 09:57 PM

Old photo restoration is a method of using artificial intelligence technology to repair, enhance and improve old photos. Using computer vision and machine learning algorithms, the technology can automatically identify and repair damage and flaws in old photos, making them look clearer, more natural and more realistic. The technical principles of old photo restoration mainly include the following aspects: 1. Image denoising and enhancement. When restoring old photos, they need to be denoised and enhanced first. Image processing algorithms and filters, such as mean filtering, Gaussian filtering, bilateral filtering, etc., can be used to solve noise and color spots problems, thereby improving the quality of photos. 2. Image restoration and repair In old photos, there may be some defects and damage, such as scratches, cracks, fading, etc. These problems can be solved by image restoration and repair algorithms

Application of AI technology in image super-resolution reconstruction Application of AI technology in image super-resolution reconstruction Jan 23, 2024 am 08:06 AM

Super-resolution image reconstruction is the process of generating high-resolution images from low-resolution images using deep learning techniques, such as convolutional neural networks (CNN) and generative adversarial networks (GAN). The goal of this method is to improve the quality and detail of images by converting low-resolution images into high-resolution images. This technology has wide applications in many fields, such as medical imaging, surveillance cameras, satellite images, etc. Through super-resolution image reconstruction, we can obtain clearer and more detailed images, which helps to more accurately analyze and identify targets and features in images. Reconstruction methods Super-resolution image reconstruction methods can generally be divided into two categories: interpolation-based methods and deep learning-based methods. 1) Interpolation-based method Super-resolution image reconstruction based on interpolation

TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year Apr 17, 2024 pm 08:00 PM

According to news from this site on April 17, TrendForce recently released a report, believing that demand for Nvidia's new Blackwell platform products is bullish, and is expected to drive TSMC's total CoWoS packaging production capacity to increase by more than 150% in 2024. NVIDIA Blackwell's new platform products include B-series GPUs and GB200 accelerator cards integrating NVIDIA's own GraceArm CPU. TrendForce confirms that the supply chain is currently very optimistic about GB200. It is estimated that shipments in 2025 are expected to exceed one million units, accounting for 40-50% of Nvidia's high-end GPUs. Nvidia plans to deliver products such as GB200 and B100 in the second half of the year, but upstream wafer packaging must further adopt more complex products.

Scale Invariant Features (SIFT) algorithm Scale Invariant Features (SIFT) algorithm Jan 22, 2024 pm 05:09 PM

The Scale Invariant Feature Transform (SIFT) algorithm is a feature extraction algorithm used in the fields of image processing and computer vision. This algorithm was proposed in 1999 to improve object recognition and matching performance in computer vision systems. The SIFT algorithm is robust and accurate and is widely used in image recognition, three-dimensional reconstruction, target detection, video tracking and other fields. It achieves scale invariance by detecting key points in multiple scale spaces and extracting local feature descriptors around the key points. The main steps of the SIFT algorithm include scale space construction, key point detection, key point positioning, direction assignment and feature descriptor generation. Through these steps, the SIFT algorithm can extract robust and unique features, thereby achieving efficient image processing.

How to do image processing and recognition in Python How to do image processing and recognition in Python Oct 20, 2023 pm 12:10 PM

How to do image processing and recognition in Python Summary: Modern technology has made image processing and recognition an important tool in many fields. Python is an easy-to-learn and use programming language with rich image processing and recognition libraries. This article will introduce how to use Python for image processing and recognition, and provide specific code examples. Image processing: Image processing is the process of performing various operations and transformations on images to improve image quality, extract information from images, etc. PIL library in Python (Pi

Examples of practical applications of the combination of shallow features and deep features Examples of practical applications of the combination of shallow features and deep features Jan 22, 2024 pm 05:00 PM

Deep learning has achieved great success in the field of computer vision, and one of the important advances is the use of deep convolutional neural networks (CNN) for image classification. However, deep CNNs usually require large amounts of labeled data and computing resources. In order to reduce the demand for computational resources and labeled data, researchers began to study how to fuse shallow features and deep features to improve image classification performance. This fusion method can take advantage of the high computational efficiency of shallow features and the strong representation ability of deep features. By combining the two, computational costs and data labeling requirements can be reduced while maintaining high classification accuracy. This method is particularly important for application scenarios where the amount of data is small or computing resources are limited. By in-depth study of the fusion methods of shallow features and deep features, we can further

See all articles