cropper+pillow處理上傳圖片剪裁(一)


在寫新博客的時候,遇到需要用戶上傳自定義圖片的處理,查了一番資料,決定用cropper和pillow來處理需要剪裁的圖片上傳,大致思路是:前端收集用戶上傳的圖片和用戶剪裁的尺寸數據,后台接收圖片后按數據進行剪裁保存,但是剪裁的臨時文件我還沒有想出一個比較合理的辦法,這里只記錄前期的簡單實現

一.cropper

github: https://github.com/fengyuanchen/cropper

 這里我按教程引入了

cropper.min.css

cropper.min.js

但是會報錯,TypeError: image.cropper is not a function直到我引入了這個解決了報錯問題,此外他們都是依賴jquery的

jquery-cropper.min.js

{#cropper編輯區域#}
<div class="avatar-wrapper" id='avatar-wrapper'>
    <img src="">
</div>
{#頭像預覽區域#}
<div class="avatar-preview" style=" border-radius: 15%">
  <
img style="width: 96px; height: 96px;" src="">
</
div> {#上傳按鈕#} <a id="upload" class="btn btn-primary">上傳頭像</a> <label class="btn btn-primary" for="avatar-input">選擇圖片</label>
{#form#}

<form action="" method="post" id="avatar_form" enctype="multipart/form-data">
    {%csrf_token%}
<input style="display:none" type="file" class="avatar-input" id="avatar-input" name="avatar_file" accept=".jpg,.jpeg,.png">
<input type="hidden" id="avatar_x" name="avatar_x">
<input type="hidden" id="avatar_y" name="avatar_y">
<input type="hidden" id="avatar_width" name="avatar_width">
<input type="hidden" id="avatar_height" name="avatar_height">
</form>

模板的主要內容就是這些,主要是編輯區域、預覽區域、上傳按鈕和隱藏的form組成,其中預覽區域可以根據自己的需求先展示原頭像或者默認頭像,通過js將圖片和尺寸數據保存在隱藏的form中上傳到后台

cropper的初始化:

var image = $('#avatar-wrapper img');
image.cropper({
    checkImageOrigin: true, //檢查圖片來源
    dragMode: 'move',   //圖片可移動
    restore:false,      //窗體調整大小之后不自動恢復裁剪區域
    zoomOnWheel: false, //不允許通過鼠標滾輪縮放
    zoomOnTouch: false, //不允許通過觸摸縮放
    aspectRatio: 1 / 1, //裁剪比例
    autoCropArea: 0.5,  //裁剪背景透明度
    autoCropArea: 1,    //自動裁剪的比例
    preview: ".avatar-preview",//預覽區域
    crop: function (e) {
    //返回圖片編輯相關數據
        $('#avatar_x').val(e.detail.x);
        $('#avatar_y').val(e.detail.y);
        $('#avatar_width').val(e.detail.width);
        $('#avatar_height').val(e.detail.height);
     },
});        

圖片上傳到cropper進行剪裁:

        $("#avatar-input").change(function(){

            var URL = window.URL || window.webkitURL;
            if(URL){
                var files = this.files;
                if (files && files.length){
                    var file = files[0];
                    if (/^image\/\w+$/.test(file.type)) {
                      var blobURL = URL.createObjectURL(file);
                      image.cropper('reset').cropper('replace', blobURL);
                      $('.avatar_crop .disabled').removeClass('disabled');
                    } else {
                      alert('請選擇一張圖片');
                    }
                }
            }
        });

上傳到后台:(我使用的jquery-form.js插件,普通的ajax方法也可以)

        $('#upload').click(function () {
                if($('#avatar-wrapper img').attr('src')==''){
                        $('#infoModal h4').html('請先選擇一個圖片')
                        $('#infoModal').modal('show')
                        return false;}
                var $form=$("#avatar_form")
                $form.ajaxSubmit(function (headpicaddress) {
                })

二.pillow

def user_my_info_headpic(request):
    # 剪裁數據獲取
    top = int(float(request.POST['avatar_y']))
    buttom = top + int(float(request.POST['avatar_height']))
    left = int(float(request.POST['avatar_x']))
    right = left + int(float(request.POST['avatar_width']))
    # 圖片臨時保存
    with open(os.path.join(settings.BASE_DIR, "test1.jpg"), "wb") as f:
        for line in request.FILES['avatar_file']:
            f.write(line)
            
    # 打開圖片
    im = Image.open(os.path.join(settings.BASE_DIR, "test1.jpg"))
    # 剪裁圖片
    crop_im = im.crop((left, top, right, buttom))
    # 保存圖片
    crop_im.save(os.path.join(settings.BASE_DIR, "test2.jpg"))
    return HttpResponse("ok")

這是我的view方法,路由部分省略了,只是簡單的保存在一個臨時位置,后面我會整理出一個更合理的方法和完整的流程

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM