CI框架学习之七 ( 常用图像处理 封装 )

其实微信手机端上图时,列表图最好是缩略图,节省流量,这不,又被移动坑了一把,话费签一分就停机,流量欠到90块才停机,我也是醉了。。。

不说废话了,下面是用CI 的内置处理图像的库写的,小弟不才,遗漏之处敬请指出,谢谢。

/**
	 * 生成缩略图
	 * @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
    	        ));
	    }
	}

下面是前端的基本html代码:

<!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="/public/img/default.png" alt="" id="sharepic_img"></p>
	</div>
</div>

<script type="text/javascript">
$(function () {

	/*****************图片上传部分开始 *******************/
	var act = "<form class='myupload' action='"+"<?php echo site_url('mytest/uploadfile');?>"+"' 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>

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-08-01 07:36:21

CI框架学习之七 ( 常用图像处理 封装 )的相关文章

CI框架学习之六 ( 常用函数封装 )

/** * 封装查询函数 */ public function get_what($table='',$where=array(),$fields = ' * '){ if( '' == $table ){ return false; } //查询并返回相关结果 $query = $this->db->select($fields)->where($where)->get($table); $res = $query->result_array(); return $res;

CI框架学习(1)-框架介绍控制器建立与访问

前言:入行算3年了,专职开始敲代码也有1年半的时间.技术底子一直很差,现在依然在菜鸟级别,上班都是无用功的忙碌很少思考终结,导致代码敲了就忘没有积累.工作期间大致使用过3个框架ecshop.ThinkPhP.CI,都是皮毛不深入,代码管理的也都很混乱.基于现在手上的项目是用CI框架,就决定系统学习下此框架,打下基础方便于以后对项目的管理. 学习形势:看视频 + 笔记(仅记录重点或不知道的知识)    视频地址(CI框架学习(1)-框架介绍控制器建立与访问) [重点1]CI框架的目录结构 appl

各种demo——CI框架学习

寒假学习一下CI框架,请各位多多指教! 一.CI的HelloWorld! 注意:CI禁止直接通过文件目录来访问控制器. ./application/controllers/hello.php 1 <?php 2 //放止用户直接通过路径来访问控制器,如果这样的话会显示找不到(封装) 3 if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 4 5 class Hello extends CI_Controller

后盾网-CI框架学习笔记

CI框架: 表单验证: 载入验证类 $this->load->library('form_validation'); 设置规则 $this->form_validation->set_rules('name值','规则'); 执行验证 $this->form_validation->run() 表单验证辅助函数: $this->load->helper('form'); 1. set_value('name') //重填数据 2. form_error('n

CI框架学习之六 ( 数据库查询缓存优化 )

CI框架中有个比较好的查询优化,就是数据库缓存优化 1.开启缓存 //在application/config.php中开启 $db['default']['cache_on'] = TRUE; //在application/config.php中开启 $db['default']['cachedir'] = './cache'; //并在对应的目录中加一个可写缓存目录cache 2. 在对应的查询中开启缓存语句 // 打开缓存开关 $this->db->cache_on(); $query =

CI框架学习笔记4——Benchmark.php

我们回到Codeigniter.php上继续往下看,第一个引入的类文件是Benchmark.php,这个文件主要是提供基准测试,具体使用方法参考手册http://codeigniter.org.cn/user_guide/libraries/benchmark.html.建议小伙伴们都读一读手册,弄懂功能的使用后,再来分析代码,才会事半功倍.不多说了,下面进入正题. 测试类定义了一个数组变量public $marker = array(),他的目的主要是用来记录我们在文件中添加的测试点. pub

CI框架学习笔记

一.CI版本 开发版本3.1.2   下载地址:https://github.com/bcit-ci/CodeIgniter/archive/3.1.2.zip 二.开发步骤 1.解压文件到www/ci 目录下 2.创建数据库 myci  后建表 user CREATE TABLE `user` ( `id` int(5) NOT NULL AUTO_INCREMENT, `uname` varchar(20) DEFAULT NULL, `age` int(2) DEFAULT NULL, `

【ci框架学习】控制器-视图

基础的东西就不写了,网上大把的教程,可以慢慢磨.这里说些要注意的要点. 1.所有控制器都必须间接或者直接继承控制器基类 CI_Controller. 2.文件命名尽量小写,因为ci使用的是pathinfo,浏览器大小写敏感. 3.$this->load->view('user');  可以加载 名为user的视图,$this->load->view('user/index') 加载在user文件夹下的index视图文件. 4.与控制器名同名的为构造函数,默认会被调用,并非想实现这样

CI框架学习笔记3——Log.php

上一节说完了Common.php,然而跟代码打交道总是免不了日志记录,所以这一节我们说说Log.php文件. 先看看类里面的几个属性, protected $_log_path;  日志路径 protected $_file_permissions = 0644; 文件权限 protected $_threshold = 1;  日志的等级,用来判断出现的错误异常什么的是否需要记录 protected $_threshold_array = array(); protected $_date_f