1. 程式人生 > >django + cropper 實現頭像預覽裁剪上傳

django + cropper 實現頭像預覽裁剪上傳

思路:

使用cropper這個前端外掛,對圖片進行裁剪,cropper生成的截圖,是一串base64的編碼,再將其轉為blob格式,傳到後端,進行儲存。簡單的說就是前端裁剪好的圖片,傳到後端,而不是將裁減的資料值傳到後端,在後端進行裁剪.

cropper的api:

cropper的簡單使用:

html

<div>
  <img id="image" src="picture.jpg">
</div>

css

img {
  max-width: 100%; /*必填*/
}

js

var $image = $('#image');

$image
.cropper({ aspectRatio: 16 / 9, crop: function(event) { console.log(event.detail.x); console.log(event.detail.y); console.log(event.detail.width); console.log(event.detail.height); console.log(event.detail.rotate); console.log(event.detail.scaleX); console.log(event.detail.scaleY); } }); //例項化
var cropper = $image.data('cropper');

使用cropper進行圖片的裁剪

匯入:
  <script src="{{STATIC_URL}}js/jquery.js"></script>
  <link  rel="stylesheet" type="text/css" href="{{STATIC_URL}}css/cropper.css" />
    <script src="{{STATIC_URL}}js/cropper.js" type="text/javascript" ></script>
css:
  body {
            font-size: 16px;
            font-family:"Microsoft YaHei",Arial, Helvetica, sans-serif
        }
        *,
        *:before,
        *:after {
            -webkit-box-sizing: border-box;
               -moz-box-sizing: border-box;
                -ms-box-sizing: border-box;
                    box-sizing: border-box;
        }

        .crop-picker-wrap {
            position: relative;
            width: 100px;
            height: 30px;
            overflow: hidden;
        }
        .crop-picker {
            width: 100%;
            height: 100%;
            line-height: 1;

            -webkit-appearance: none;
            margin: 0;
            border: none;
            border-radius: 5px;
            padding: 9px 0;
            background-color: #1ab2ff;

            color: #fff;            
            cursor: pointer;
        }
        .crop-picker-file {
            position: absolute;
            top: 0;
            right: 0;
            height: 100%;
            opacity: 0;
            cursor: pointer;
            filter: alpha(opacity=0);
        }

        .crop-save,
        .crop-cancel {
            display: inline-block;
            vertical-align: middle;

            width: 150px;
            height: 50px;
            line-height: 50px;

            -webkit-appearance: none;
            margin: 0 5px;
            border: none;
            border-radius: 5px;
            background-color: #1ab2ff;

            color: #fff;
            cursor: pointer;
        }

/* Apply these styles only when #preview-pane has
   been placed within the Jcrop widget */
.jcrop-holder #preview-pane {
  display: block;
  position: absolute;
  z-index: 2000;
  top: 10px;
  right: -280px;
  padding: 6px;
  border: 1px rgba(0,0,0,.4) solid;
  background-color: white;

  -webkit-border-radius: 6px;
  -moz-border-radius: 6px;
  border-radius: 6px;

  -webkit-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
  -moz-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
  box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
}

/* The Javascript code will set the aspect ratio of the crop
   area based on the size of the thumbnail preview,
   specified here */
#preview-pane {
 float:right;
 }

#preview-pane .preview-container {
  overflow: hidden;
  border-style: groove;
  background-color: black;
  width: 160px;
  height: 160px;
}

#target {
    max-width: 100%; /* This rule is very important, please do not ignore this! */
}

.cut-container{
        width: 300px;
        height: 300px;
        margin:20px 30px;
        border:dashed #cacaca 1px;
}

#preview{
   max-width: 300px;
   max-height:300px;
}

#cropper-line{
      border-color:black;
}
   <div class="crop-picker-wrap">
      <button class="crop-picker" id='select' type="button">選擇圖片</button>
     <input type="file" class="crop-picker-file" id="inputImage" name="file" accept=".jpg,.jpeg,.png,.gif,.bmp,.tiff">>
        </div>
    //預覽
  <div id="preview">
             {% if thumb_pic %}
             <img src="{{MEDIA_URL}}{{thumb_pic}}" id="target" />   
             {% else%}
             <img src="" id="target" /> 
             {% endif %}    
               <span>滾動放大或縮小</span> 
          </div>
            // 顯示裁剪的效果圖
          <div id="preview-pane">
            <div class="preview-container">
                 <img src="" id="cut_thumb"/>
            </div>
            <span>160*160</span>
          </div>

           <div class="crop-operate">
                <button class="crop-save" type='submit' id='save'>儲存</button>
                <button class="crop-cancel" type="button" id='cancel'>取消</button>
            </div>

效果如下:

使用滾輪進行圖片放大縮小,寬高是360*360
這裡寫圖片描述

js:
var $image = $('#target');  
        $('[type=file]').change(function(e) {      
            var file = e.target.files[0]
            if(file.size>= 2*1024*1024){
                  layer.alert('您上傳的頭像大於2M,請重新上傳', {
                      title:'提示',
                      icon: 0,
                      skin:'layui-layer-lan', //該面板由layer.seaning.com友情擴充套件。關於面板的擴充套件規則,去這裡查閱
                    });
                }
            else{
                    var reader = new FileReader();
                    reader.readAsDataURL(file); 
                    reader.onload=function(e){
                    $image.attr("src",e.target.result)
                     $image.cropper('reset', true).cropper('replace',e.target.result);
                    }
                    if(($('#target').attr('src').length) != 0){
                         $('#preview').show()
                         $('#preview-pane').show()
                         $('.crop-operate').show()
                    } 
                }
          })
            $image.cropper({
                        dragMode: 'move',
                        viewMode:3,
                        aspectRatio:1,//1 / 1,  //圖片比例,1:1
                        minCropBoxWidth:300,
                        minCropBoxHeight:300,
                        minContainerWidth:300,
                        minContainerHeight:300,
                        restore: false,
                        guides: false,
                        center: false,
                        highlight: false,
                        cropBoxMovable: false,
                        cropBoxResizable: false,
                        toggleDragModeOnDblclick: false,
                        modal:false,
                        responsive:false,
                        preview:'.preview-container',
                        background:false,     
                     });

 $('#thumb_upload').submit(function(){
      event.preventDefault();  
      // 獲取裁圖後圖片的base64
     var $imgData=$image.cropper('getCroppedCanvas')
      var dataurl = $imgData.toDataURL('image/jpeg');
     // 將base64 轉為 blob格式
      var b64 = dataurl.split(',')[1];
     var binary = atob(b64);
     var array = [];
     for (var i = 0; i < binary.length; i++) {
         array.push(binary.charCodeAt(i));
     }
     var blob =  new Blob([new Uint8Array(array)], {type: 'image/jpeg'})
     // 使用FormData()進行ajax請求,上傳圖片
     var formData = new FormData()
     // 圖片名字
     var img_name = new Date().getTime()+'.jpg';
     formData.append('csrfmiddlewaretoken','{{ csrf_token }}')
     formData.append('uploadFile',blob,img_name)
     var data = formData
      $.ajax({
           url: "/上傳地址/",
           type: "post",
           dataType: "json",
           data:data,
           processData: false,
           contentType:false,
           success:function(result){
               if(result['state']==0){
                    layer.close(layer.index);  
                    window.parent.location.reload();
               }
               if(result['state']==1){
                     layer.alert('上傳失敗,請聯絡客服', {
                          title:'提示',
                          icon: 0,
                          skin: 'layui-layer-lan'//該面板由layer.seaning.com友情擴充套件。關於面板的擴充套件規則,去這裡查閱
                        },
                          function (){
                             window.parent.location.reload()
                        }
                    );      
               }
           }
      });
  });

  $('#cancel').click(function(){
      event.preventDefault();
      var index = parent.layer.getFrameIndex(window.name);  
      parent.layer.close(index);  
  })

</script>   

django後臺:

    def post(self,request):
        try:
            id =request.user.id
            #  獲取資料庫
            user = 使用者.objects.get(id=id)
            #  上傳的圖片
            thumb_file = request.FILES['uploadFile']
            user.picture = thumb_file
            user.save()
            to_json_response = {
                        'state':0
                        }
        except Exception as e:
            print(e)
            to_json_response={
                    'state':1
                }
        return HttpResponse(json.dumps(to_json_response), content_type='application/json')

相關推薦

django + cropper 實現頭像裁剪

思路: 使用cropper這個前端外掛,對圖片進行裁剪,cropper生成的截圖,是一串base64的編碼,再將其轉為blob格式,傳到後端,進行儲存。簡單的說就是前端裁剪好的圖片,傳到後端,而不是將裁減的資料值傳到後端,在後端進行裁剪. cropper

利用FileReader和FormData實現圖片(base64轉二進位制檔案)

業務有個需求,要做圖片預覽上傳,過去都是客戶端上傳給後端,後端返回 url 前端進行預覽,現在其實可以不依賴後端做預覽,最後在上傳,這主要依賴 FileReader 和 FormData 這兩個物件和 JavaScript 處理二進位制的能力。 OK,Show cod

Django+jQuery cropper實現使用者頭像裁剪, [原創]

{% extends "account/base.html" %} {% load static %} {% block content %} {% if user.is_authenticated %} | <a href="{% url 'account_email' %}">Manage

基於“formData批量的多種實現” 的多圖片的多種實現 formData批量的多種實現

  前言   圖片上傳是web專案常見的需求,我基於之前的部落格的程式碼(請戳:formData批量上傳的多種實現)裡的第三種方法實現多圖片的預覽、上傳,並且支援三種方式新增圖片到上傳列表:選擇圖片、複製貼上圖片、滑鼠拖拽圖片,同時支援從上傳列表中移除圖片(點選“X”號)      效果演示   選擇

使用input[type=file]原生實現圖片的

1. 模仿表單提交: 建立一個FormData物件          呼叫它的 append() 方法來新增欄位 // formData.append(key, value); var fd = new FormData(); fd.append("username",

jquery擴充套件html5+canvas實現多張圖片 壓縮

主要javascript程式碼 (function($){ $.fn.extend({ aiiUpload:function(obj) { if(typeof obj !="object") { alert('引數錯誤'); retur

移動端HTML5 檔案

本文主要介紹使用HTML5 圖片上傳及上傳前的預覽。本人是做PHP後端的,由於前端有時也需要自己寫,有空就研究了下圖片上傳預覽,寫的都是原生程式碼,廢話不多說,直接上程式碼。 前端程式碼 <!DOCTYPE html> <html lang

js圖片,前端修改檔名

<!doctype html><html lang="en"><head>    <meta charset="UTF-8">    <title>Demo</title>   <!--  IE需要

html5圖片的功能

html5支援圖片預覽 具體程式碼:上傳頁面 upload_h5.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>使用html5

前端input的圖片

既然要實現在前端預覽上傳的圖片,我們需要先了解input 和 file型別 Input 標籤的file型別,提供了上傳檔案的功能,通過此型別,可以上傳檔案到伺服器。 input的file型別,在上傳檔案時,會返回一個File物件,這個物件會存在一個FileList數組裡邊

Vue.js 2.0 移動端拍照壓縮圖片

在學習和使用Vue.js 2.0 的過程中遇到不少不一樣的地方,本來移動端開發H5應用,準備將mui框架和Vue.js+vue-router+vuex 全家桶結合起來使用,但是在拍照上傳的實現過程中遇到了無法呼叫plus的H5+介面的問題,所以最後拍照上傳功能還是使用input file方式裡解決的。但是

ionic3從手機相簿選擇多張照片到伺服器

安裝外掛①image-picker選擇多張照片--參照https://ionicframework.com/docs/native/image-picker/命令--ionic cordova plugin add cordova-plugin-telerik-imagepi

H5圖片(WEB前端)

web上傳圖片很簡單,網上有許多的demo和js,但是本人嫌棄用那些會引入許多js包,所以還是用原生的jquery來寫吧。 一、html佈局檔案 html有一個自己的上傳檔案控制元件---input,只需要將其type屬性設定為file即可上傳檔案,accept=“image/”是用來限制檔案型別為imag

基於jQuery和cropper點選頭像裁剪圖片

使用jquery上傳前,預覽圖片,裁剪,示例使用php接收上傳的檔案,並且儲存為裁剪後的圖片。不需要上傳後再裁剪圖片,只需要本地裁剪好即可,裁剪的時候也可以旋轉圖片。裁剪控制元件使用了,cropper。 html程式碼 <!DOCTYPE html> <html la

Jcrop外掛+Canvas實現圖片+圖片裁剪

前言 想實現一個功能:使用者點選上傳按鈕,選擇圖片後。圖片顯示在一個彈出框上,並可以對圖片進行裁剪。裁剪後的圖片顯示在頁面上。提交表單即可上傳圖片。 遇到問題 瀏覽器的安全設定不讓使用者獲取上傳的圖片路徑,實際獲取的是c:\fakepath\a.jp

web 圖片實現本地

UNC view 使用 區別 lec F5 sed 邊界 urn 在說上傳之前先說說如何替換or美化瀏覽器自帶的簡陋上傳按鈕(自定義自己的上傳按鈕 如:img): 1.將自定義上傳按鈕上方添加 input file 框,實現input實現透明處理。 2.對自定義

使用JCrop進行圖片裁剪裁剪js說明,裁剪裁剪裁剪設計的圖片處理的工具類和程式碼

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!        

Vue 實現圖片裁剪並獲取被裁剪區域的base64(無元件)

前言     最近公司專案需要用到圖片裁剪技術,便著手寫了一個,可以說是用Vue實現的原生裁剪,畢竟也只是去操作dom,不過vue有個黑魔法,ref屬性,使用的方法和原生dom一模一樣但是更節省dom操作時的消耗 裁剪思路 這邊大致介紹一下裁剪圖片的思路

bootstrap+fileinput外掛實現照片功能

            圖片.png實際專案中運用:圖片.png功能:實現上傳圖片,更改上傳圖片,移除圖片的功能<!DOCTYPE html><html>    <head>        <metacharset="UTF-8">        <tit

input file 方式圖片並實現實時

用普通的html的 <input type="file"/> 標籤是不能實現實時預覽功能的,獲取表單的值可以得到圖片所在路徑:C:\fakepath\test.png,如果將它直接賦值給img標籤的href屬性,會報錯:Not allowed to load lo