代码改变世界

上传自定义水印图片到图片空间及保存数据库的方法

  流浪的诗人  阅读(599)  评论(0编辑  收藏  举报

(1)、添加我的水印,按钮展示:

1
2
3
4
5
6
7
8
9
<div class="form-actions">
       <button data-toggle="modal" class="sui-btn btn-primary btn-large" onclick="addmywatermark();" >添加我的水印</button>
    </div>
   /**
   * 添加我的水印
   **/
   function addmywatermark(){
       $("#bjtp").modal('show');
   }

(2)、按钮点击的上传图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/*
   * id="bjtp",modal页面展示
   */
   <div id="bjtp" tabindex="-1" role="dialog" data-hasfoot="true" data-backdrop="static" class="sui-modal hide fade" data-width="500px" >
   <div class="modal-dialog">
   <div class="modal-content">
     <div class="modal-header">
     <button type="button" data-dismiss="modal" aria-hidden="true" class="sui-close">×</button>
        <h4 id="myModalLabel" class="modal-title">添加我的水印模板</h4>
     </div>
    <div class="modal-body" >
    <form class="sui-form"  id="picfile" name="picfile" >
   <label class="control-label">上传图片 :</label>
   <div class="controls">
       <span>
       <input type="hidden" id="user_nick" name="user_nick"/>
       <input type="file" id="file" name="file" style="display:none;" onchange="previewImageLogo(this);"/>
       <button type="button" class="sui-btn btn-primary" onclick="file.click()" value="">浏览本地图片</button>
       <div id="pic_logo"><img src="" width="100mm" id="logopic" height="100mm"/></div>
   </div><br/>
   </form>
    </div>
     <div class="modal-footer">
        <button  data-ok="modal" data-toggle="modal"  data-keyboard="false" class="sui-btn btn-primary btn-lg" onclick="getpicspaceimages();">确定</button>
        <button type="button" data-dismiss="modal" class="sui-btn btn-default btn-large">关闭</button>
    </div>
   </div>
   </div>
 </div>

 (3)、浏览本地图片,确定上传按钮

复制代码
function getpicspaceimages(){
    $("#user_nick").val(user_nick);
    var form = document.getElementById("picfile");/*form表单用于上传文件,ajax请求发送formData*/   
    var formData = new FormData(form);   
    console.log("formData:"+formData);
    $.ajax({    
        url: APP_WEB_INDEX_ROOT+'/itemdb2/uploadimgs',        
        type: 'POST',              
        data: formData,              
        cache: false,        
        contentType: false,        
        processData: false,
        dataType:'json',                
        beforeSend: function(data){ },      
        success: function(data){
            console.log(data);
            if(data=='fail'){
                layer.msg('上传图片失败!', 1, 3);
            }else{
                layer.msg('上传图片成功!', 2, 1);
                showownmarkimgs();/*提取数据库数据,运用dot模板展现所有的自定义水印模板*/
            }
        },       
        error: function(data){
            layer.msg('上传图片失败!', 1, 3);
        }   
    });
}
复制代码

 

(4)、上传水印图片后台代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
function uploadimgsAction(){
    log_message("info",'进来了!');
    $nick = $_POST['user_nick'];
    if(empty($nick)){
        return 'fail';
    }
    $picture_category_id = $_POST['category_id'];
    $this->log("resp:".json_encode($nick));
   
    $scp = $_FILES['file'];
    $logo_name = $scp["tmp_name"];
    $this->log("scp:".$scp.",logo_name:".$logo_name);
    if ($_FILES["file"]["error"] > 0){
        $this->log_error('-','自定义水印上传图片空间','uploadimgsAction',"上传失败:文件出错");
        echo json_encode("fail");
    }else{
        $pinfo = pathinfo($_FILES["file"]["name"]);
        $photo_type = $pinfo['extension'];
        $pic_name = md5(microtime(true)).".".$photo_type;
        $pic_path = "/data/tmp/".$pic_name;  /*定义临时文件夹用于存放水印图片*/
        $this->log("pic_path:".$pic_path);
 
        if(!move_uploaded_file ($_FILES["file"]["tmp_name"], $pic_path)){
            /*
            *move_uploaded_file() 函数将上传的文件移动到新位置。
            *若成功,则返回 true,否则返回 false。
            *
            */
            $this->log_error('自定义水印上传图片空间','uploadimgsAction',"上传失败:不是合法的上传文件");
            echo json_encode("fail");
        }else{
            //获取用户session
            $token_result = $this ->Authorization( $nick, 'item' );
            if( $token_result && $token_result ->code == 200 ){
                $top_session = $token_result ->msg;
                $this->log($top_session);
            }else{
                $this->log("没有获得用户的topsso授权信息");
                $this->log_error('自定义水印上传图片空间','uploadimgsAction',"上传失败:不是合法的上传文件");
                echo json_encode("fail");
                return 'fail';
            }
            //PictureCategoryGetRequest,淘宝适用于php的api,用于得到图片空间文件夹,存放水印
            $c = new TopClient;
            $c->appkey = $this -> app_itemkey;
            $c->secretKey = $this -> secret_itemKey;
            $cname = '勿删爱用商品自定义水印';
            $req = new PictureCategoryGetRequest;
            $req->setPictureCategoryName($cname);
            $resp = $c->execute($req, $top_session);
            if(isset($resp ->picture_categories ->picture_category)){
                $pictureCategoryId = $resp ->picture_categories ->picture_category[0] ->picture_category_id;
            }
            $this->log('pid :'.$pictureCategoryId);
            //没有获取到保存水印的类目id,setPictureCategoryName需要创建
            if(empty($pictureCategoryId)){
                $req = new PictureCategoryAddRequest;
                $req->setPictureCategoryName($cname);
                // $req->setParentId("0");
                $resp = $c->execute($req, $top_session);
                $this->log('pid_add:'.json_encode($resp));
            }
             
            $req = new PictureUploadRequest;
            $this->log($picture_category_id .'                # 149311130066704700');
            $req->setPictureCategoryId(intval($pictureCategoryId));
            $req->setImg('@' . $pic_path);
            $req->setImageInputTitle($pic_name);
            $req->setClientType("client:computer");
            $resp = $c->execute($req, $top_session);
            unlink($pic_path);  //图片上传成功后,删除临时文件夹中的图片
            //从返回值中获取数据
            $this->log(json_encode($resp));
            $picture_path = $resp->picture->picture_path;
            $createtime = $resp->picture->created;
            $picture_category_id = $resp->picture->picture_category_id;
            $pixel = $resp->picture->pixel;
            $sizes = $resp->picture->sizes;
            $picture_id = $resp->picture->picture_id;
            
            //水印图上传到图片空间之后,同时保存到数据库
             if (!empty($nick)){
                $this -> log("nick22222222:".$nick);
                if (strpos($nick, ':') != false) {
                    $nick = substr($nick, 0, strpos($nick, ':'));
                }
                $usersuggest = array(
                    'sellernick' => $nick,
                    'pic_url' => $picture_path,
                    'createtime'=> $createtime,
                    'picture_category_id' => $picture_category_id,
                    'pixel'=> $pixel,
                    'sizes'=> $sizes,
                    'num_iid'=>$picture_id
                );
                $dao = new CommonDao();
                $id = $dao -> saveRow('zzbitem.watermark_userown', $usersuggest, '');
                if($id > 0){
                    //图片保存成功之后,需要取出图片展现在前台
                    $this->log("picture_path222:".$picture_path);
                    $waterImg = $picture_path;
                    $handle = fopen($waterImg, 'rb');//打开水印图片
                    $watermark = new Imagick();
                    $watermark->readImageFile($handle);
                    $size_w = $watermark->getImagePage();//获取水印图片大小
                    $height_w = $size_w['height'];//水印图片高
                    $width_w = $size_w['width'];//水印图片宽
                    $this->log("打开水印,高度{$height_w},宽度{$width_w}");
 
                    if($width_w/3 > $height_w){
                        $width_w = 150;//默认单位为px
                        $height_w = 30;
                    }else if($height_w/3 > $width_w){
                        $width_w = 30;
                        $height_w = 150;
                    }else{
                        $width_w = 150;
                        $height_w = 100;
                    }
                    
                    $picvar = array($waterImg,$width_w,$height_w,$picture_id);
                    $this->log("picarr:".json_encode($picvar));
                    echo json_encode($picvar);
                }else{
                    echo json_encode("fail");
                }
            }
            
        }
    }
}

  

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示