js无刷新上传图片,服务端有生成缩略图,剪切图片,iphone图片旋转判断功能

Posted nike_ha

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js无刷新上传图片,服务端有生成缩略图,剪切图片,iphone图片旋转判断功能相关的知识,希望对你有一定的参考价值。

html

<form action="<{:AppLink(‘circle/uploadimg‘)}>" id="imageform" method="post" enctype="multipart/form-data">
     <input name="photoimg" type="file" id="xwzx_f" style="display: none;" />
</form>

 

 

js:

        <script src = "__TMPL__statics/js/jquery-1.7.1.min.js?v=20161123" ></script>
        <script src="__TMPL__statics/js/layer/layer.js?v=20161123"></script>
        <script src = "__TMPL__statics/js/jquery.form.js?v=1"></script>

$("#xwzx_f").change(function(){
    $(".loading-gif").show();
    var img_name=this["files"][0]["name"];
    var temparr=img_name.split(‘.‘);
    var ext=temparr.pop().toLowerCase();
    temparr=null;
    if(ext!="jpg"&&ext!="png"&&ext!="gif"&&ext!="bmp"&&ext!="jpeg"&&ext!="jepg"){
        layer.msg(‘上传的格式不正确‘);
        $(".loading-gif").hide();
        return false;
    }
    var src = window.URL.createObjectURL(this["files"][0]);//如果预览可用此代码
    
    $(‘#imageform‘).ajaxSubmit({
        beforeSend: function() {
             $(".loading-gif").html( ‘0%‘);

        },
        uploadProgress: function(event, position, total, percentComplete) {
             $(".loading-gif").html(percentComplete + ‘%‘);
        },
        success: function() {
            $(".loading-gif").hide();
        },
        complete: function(xhr) {
            var result=JSON.parse(xhr.responseText);
             if(result.status=="success"){
                var htmlstr="";
                htmlstr=‘<li class="l_up_img"><div class="f-img-box">‘;
                htmlstr+=‘<a href="javascript:;"><img src="__ROOT__/attachs/qz/‘+result.imgpath+‘"></a>‘;
                htmlstr+=‘<input class="up_img" type="hidden" value="‘+result.imgpath+‘" bmw="‘+result.bm_w+‘" bmh="‘+result.bm_h+‘"/>‘;
                htmlstr+=‘</div></li>‘;
                $(".f-s-img").find("li").last().before(htmlstr);
            }else{
                layer.msg(result.msg);
            }
        }
    });

 

 

php代码(携带生成大中小缩略图,剪切功能,iphone图片旋转,iphone旋转需要php.ini开启php_exif)

function imgturn($src, $direction = 1,$ext) {
        switch ($ext) {
            case ‘gif‘ :
                $img = imagecreatefromgif ( $src );
                break;
            case ‘jepg‘:
            case ‘jpg‘ :
            case ‘jpeg‘ :
                $img = imagecreatefromjpeg ( $src );
                break;
            case ‘png‘ :
                $img = imagecreatefrompng ( $src );
                break;
            default :
                die ( ‘图片格式错误!‘ );
                break;
        }
        $width = imagesx ( $img );
        $height = imagesy ( $img );
        $img2 = imagecreatetruecolor ( $height, $width );
        // 顺时针旋转90度
        if ($direction == 1) {
            for($x = 0; $x < $width; $x ++) {
                for($y = 0; $y < $height; $y ++) {
                    imagecopy ( $img2, $img, $height - 1 - $y, $x, $x, $y, 1, 1 );
                }
            }
        } else if ($direction == 2) {
            // 逆时针旋转90度
            for($x = 0; $x < $height; $x ++) {
                for($y = 0; $y < $width; $y ++) {
                    imagecopy ( $img2, $img, $x, $y, $width - 1 - $y, $x, 1, 1 );
                }
            }
        }
        switch ($ext) {
            case ‘jepg‘:
            case ‘jpg‘ :
            case "jpeg" :
                imagejpeg ( $img2, $src, 100 );
                break;
            
            case "gif" :
                imagegif ( $img2, $src, 100 );
                break;
            
            case "png" :
                imagepng ( $img2, $src, 100 );
                break;
            
            default :
                die ( ‘图片格式错误!‘ );
                break;
        }
        imagedestroy ( $img );
        imagedestroy ( $img2 );
    }
    
    
    /**
     * 上传图片
     */
    public function uploadimg(){
        if(isset($_POST) and $_SERVER[‘REQUEST_METHOD‘] == "POST"){
            $name = $_FILES[‘photoimg‘][‘name‘];
            $size = $_FILES[‘photoimg‘][‘size‘];
            
            try {
                $filetemp=date(‘Ymd‘,time());
                $path = BASE_PATH."/attachs/qz/{$filetemp}/";//需要上传的路径
                if(!is_dir($path)){
                    mkdir($path,0777,true);
                }
            } catch (Exception $e) {
                die(json_encode(array(‘status‘=>‘error‘,‘msg‘=>‘文件路径创建失败‘)));
            }
            
            if(empty($name)){
                die(json_encode(array(‘status‘=>‘error‘,‘msg‘=>‘请选择要上传的图片‘)));
            }
            
            if($size>(1024*1024*10)){
                die(json_encode(array(‘status‘=>‘error‘,‘msg‘=>‘图片大小不能超过10M‘)));
            }
            
            $extend = pathinfo($name);
            $ext = strtolower($extend["extension"]);
            
            if(!in_array($ext, array(‘jpg‘,‘png‘,‘gif‘,‘bmp‘,‘jpeg‘,‘jepg‘))){
                die(json_encode(array(‘status‘=>‘error‘,‘msg‘=>‘图片格式不正确‘.$ext)));
            }
            
            $image_name = time().rand(100,999).".".$ext;
            $tmp = $_FILES[‘photoimg‘][‘tmp_name‘];
            
            /**
             *iphone判断图片方向,是否需要旋转图片
             */
            if(strpos($_SERVER[‘HTTP_USER_AGENT‘], ‘iPhone‘)&&in_array($ext, array(‘jpg‘,‘png‘,‘gif‘,‘jpeg‘,‘jepg‘))){
                $exif =exif_read_data($tmp);
                switch ($exif[‘Orientation‘]){
                    case 6:
                        self::imgturn($tmp,1,$ext);
                        break;
                    case 3:
                        self::imgturn($tmp,1,$ext);
                        self::imgturn($tmp,1,$ext);
                        break;
                    case 8:
                        self::imgturn($tmp,2,$ext);
                        break;
                }
            }
            
            
            self::imagecropper($tmp, $path,$image_name, ‘sm_‘, 150, 150);//小图,如果图片尺寸不合适就裁剪
            self::imagecropper($tmp,$path,$image_name,‘mm_‘,256,256);//中图,如果图片尺寸不合适就裁剪
            
            if($result=move_uploaded_file($tmp, $path.$image_name)){
                
                /**
                 * 修改,大图
                 */
                $imagesize=getimagesize($path.$image_name);//高,宽,格式,高宽字符串
                if($imagesize[1]>700){//宽度大于720
                    self::thumb($path,$image_name,‘bm_‘,700,700*$imagesize[1]/$imagesize[0]);//高度等比
                }else{
                    self::thumb($path,$image_name,‘bm_‘,$imagesize[0],$imagesize[1]);
                }
                /**
                 * 修改end
                 */
                
                /**
                 *生成缩略图
                 *小图  92*92
                 *中图  256*256
                 *大图  暂时不生成但预留
                 */
                /* self::thumb( $path,$image_name,‘sm_‘,92,92);
                self::thumb( $path,$image_name,‘mm_‘,256,256);
                $imagesize=getimagesize($path.$image_name);//高,宽,格式,高宽字符串
                if($imagesize[1]>720){//宽度大于720
                    self::thumb( $path,$image_name,‘bm_‘,720,720*$imagesize[1]/$imagesize[0]);//高度等比
                }else{
                    self::thumb( $path,$image_name,‘bm_‘,$imagesize[0],$imagesize[1]);
                } */
                unlink($path.$image_name);
                $filetemp=date(‘Ymd‘,time());
                $r_data=array(
                            //‘oror‘=>$exif[‘Orientation‘],
                            ‘status‘=>‘success‘,
                            ‘msg‘=>‘上传成功‘,
                            ‘imgpath‘=>$filetemp.‘/sm_‘.$image_name,
                            ‘bm_w‘=>$imagesize[0],  //大图宽
                            ‘bm_h‘=>$imagesize[1]   //大图高
                        );
                
                /* $myfile = fopen("C:/Users/sss/Desktop/ss/testfile.txt", "w+");
                fwrite($myfile, json_encode($r_data));
                fclose($myfile); */
                
                echo json_encode($r_data);
            }else{
                echo json_encode(array(‘status‘=>‘error‘,‘msg‘=>‘上传失败‘,‘oror‘=>$result));
            }
        }else{
            die(json_encode(array(‘status‘=>‘error‘,‘msg‘=>‘请求方式不正确‘)));
        }
    }
    
    
    /**
     * 创建图片缩略图
     * @param string $directroy   上传至目录,
     * @param string $doUpFile   上传的文件名,
     * @param string $dscChar   前缀,小图 sm,中图 mm ,大图 bm
     * @param number $width
     * @param number $height
     * @return string|boolean
     */
    function thumb( $Directroy,$doUpFile,$dscChar = ‘sm_‘,$width = 92, $height = 92){
        if ($doUpFile != ‘‘) {
            $srcFile = $doUpFile;
            $dscFile = $Directroy . $dscChar . $srcFile;
            $data = getimagesize($Directroy . $srcFile); // 文件格式,其值 1 为 GIF 格式、 2 为 JPEG/JPG 格式、3 为 PNG 格式。
            switch ($data[2]) {
                case 1:
                    $im = @imagecreatefromgif($Directroy . $srcFile);
                    break;
                case 2:
                    $im = @imagecreatefromjpeg($Directroy . $srcFile);
                    break;
                case 3:
                    $im = @imagecreatefrompng($Directroy . $srcFile);
                    break;
            }
            $srcW = imagesx($im);
            $srcH = imagesy($im);
            $ni = imagecreatetruecolor($width, $height);
            //imagecopyresized($ni, $im, 0, 0, 0, 0, $width, $height, $srcW, $srcH);
            imagecopyresampled($ni, $im, 0, 0, 0, 0, $width, $height, $srcW, $srcH);
            $cr = imagejpeg($ni, $dscFile);
            chmod($dscFile, 0777);
            if ($cr) {
                return $dscFile;
            } else {
                return false;
            }
        }
    }
    
    /**
     *
     * @param unknown $source_path      源图路径
     *  $Directroy,
     *  $doUpFile,
     *  $dscChar = ‘sm_‘,
     * @param unknown $target_width     目标图宽度
     * @param unknown $target_height    目标图高度
     * @return boolean
     *
     */
    function imagecropper($source_path, $Directroy,$doUpFile, $dscChar = ‘sm_‘, $target_width=92, $target_height=92){
        $srcFile = $doUpFile;
        $dscFile = $Directroy . $dscChar . $srcFile;
    
    
        $source_info   = getimagesize($source_path);
        $source_width  = $source_info[0];
        $source_height = $source_info[1];
        $source_mime   = $source_info[‘mime‘];
    
        $source_ratio  = $source_height / $source_width;
        $target_ratio  = $target_height / $target_width;
    
         
        if ($source_ratio > $target_ratio){      // 源图过高
            $cropped_width  = $source_width;
            $cropped_height = $source_width * $target_ratio;
            $source_x = 0;
            $source_y = ($source_height - $cropped_height) / 2;
        } elseif ($source_ratio < $target_ratio){   // 源图过宽
            $cropped_width  = $source_height / $target_ratio;
            $cropped_height = $source_height;
            $source_x = ($source_width - $cropped_width) / 2;
            $source_y = 0;
        }else{  // 源图适中
            $cropped_width  = $source_width;
            $cropped_height = $source_height;
            $source_x = 0;
            $source_y = 0;
        }
    
        switch ($source_mime){
            case ‘image/gif‘:
                $source_image = imagecreatefromgif($source_path);
                break;
            case ‘image/jpeg‘:
                $source_image = imagecreatefromjpeg($source_path);
                break;
            case ‘image/png‘:
                $source_image = imagecreatefrompng($source_path);
                break;
            default:
                return false;
                break;
        }
    
        $target_image  = imagecreatetruecolor($target_width, $target_height);
        $cropped_image = imagecreatetruecolor($cropped_width, $cropped_height);
    
        // 裁剪
        imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height);
        // 缩放
        imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $target_width, $target_height, $cropped_width, $cropped_height);
    
        header(‘Content-Type: image/jpeg‘);
        imagejpeg($target_image,$dscFile);
        imagedestroy($source_image);
        imagedestroy($target_image);
        imagedestroy($cropped_image);
    }

 




































































































































































































































































































































以上是关于js无刷新上传图片,服务端有生成缩略图,剪切图片,iphone图片旋转判断功能的主要内容,如果未能解决你的问题,请参考以下文章

[AWS][Serverless] 无服务器Serverless 图像缩略图应用

使用FileUpload控件上传图片并自动生成缩略图自动生成带文字和图片的水印图

上传脚本,裁剪/剪切缩略图

高并发图片(缩略图)处理中间层服务架构设计

服务器中 JS如何读取本地图片

生成缩略图的PHP上传图片类