简体   繁体   English

python django-使用解码的base64写入时图像为空白

[英]python django - Images are blank when written using decoded base64

My django website aims at allowing users to combine different clothing picture on one single canvas. 我的django网站旨在允许用户在一张画布上组合不同的服装图片。

However, the saved image is blank. 但是,保存的图像为空白。

I have applied one fiddle, please see here . 我已经装了一个小提琴,请在这里查看

I've used the methods recommended by some forums. 我使用了一些论坛推荐的方法。

Here is the views.py 这是views.py

@csrf_protect
@csrf_exempt 
def savewearingimg(request):

    imgEncodeString = request.POST.get('imgBase64')
    if request.method == 'POST' and request.is_ajax():

        singleItemNames = request.POST.getlist('singleItemNames[]') 
        saveWearingName = request.POST.get('saveWearingName') #string
        positionsX = request.POST.getlist('positionsX[]')
        positionsY = request.POST.getlist('positionsY[]')
        userWidths = request.POST.getlist('sizes[]') 

        imgEncodeString = request.POST.get('imgBase64').partition(",")[2]#for header removing
        img64Data = base64.b64decode(imgEncodeString) #other decoding fundctions failed
        BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        preFileStr = os.path.join(BASE_DIR, "media\\photos\\wearing\\")
        poFileStr=str(request.user)+'_itemName_'+saveWearingName+'.jpg'
        filename = preFileStr +poFileStr

        with open(filename, 'wb') as f:
            f.write(img64Data)

    return render(request,'combinewearing.html')

And here is part of the javascript combinewearing.js 这是javascript Combinewearing.js的一部分

$(function() {
   canvas = document.getElementById('save-canvas');
    context = canvas.getContext('2d');
});

 $('#saveWearingBtn').click(function(){

        drawToSave(alreadyPutImg,originalWidths);
     });
 function drawToSave(alreadyPutImg,originalWidths){

        loadImagesMike(sources, function(images_) { //the original author is Mike
            for(var i=0; i<ImgPutArr.length; i++ ){
                var img_iter = ImgPutArr[i];
         context.drawImage(images_[i],img_iter.x,img_iter.y,img_iter.w,img_iter.h);
                console.log('images_[i]: '+images_[i] );//[object HTMLImageElement]
                i++;
            }

        });


        var myDataURL = canvas.toDataURL(); 
        $.ajax({
          type: "POST",
          url: "/savewearingimg/",
          data: {
             'csrfmiddlewaretoken': "{{ csrf_token }}",
             'imgBase64': myDataURL,
             'singleItemNames': alreadyPutName,//array storing what users have added to the canvas
             'saveWearingName':$('#saveWearingName').val(), //end-users can customized his/her desired wearing title
             'positionsX':positionsX, //position array storing every clothing pictures
             'positionsY':positionsY,
             'sizes':sizes,
          },

        }).done(function(o) {
            alert('saved');
          console.log('saved');

        });/*end ajax*/
     } 
/*sources is an array storing all the user-selected pictures absolute path*/
function loadImagesMike(sources, callback) {
    var images = [];
    var loadedImages = 0;
    var numImages = 0;
    // get num of sources
    for(var src in sources) {
      numImages++;
    }
    for(var src in sources) {
      images[src] = new Image();
      images[src].onload = function() {
        if(++loadedImages >= numImages) {
          callback(images);
        }
      };
      images[src].src = sources[src];
    }
  }

There is no error message. 没有错误信息。 Only the image is blank. 仅图像为空白。

However, if I follow the same steps and same string as this link suggests, the image would not be blank. 但是,如果我按照此链接的建议执行相同的步骤和相同的字符串,则该图像将不会为空白。

So I suppose that the problem is due to the string's content. 所以我想问题出在字符串的内容上。 My failed string content links to this google doc link (Correct me if I'm wrong, thank you.) 我失败的字符串内容链接到此google doc链接 (如果我输入错了,请纠正我,谢谢。)


I've just found that this rectangle will show up in the image.... So what should I adjust? 我刚刚发现该矩形将显示在图像中。...那我该怎么调整?

context.rect(20, 20, 150, 100);
context.stroke();

I have solved this problem by moving THIS PART to the interior of the loadImagesMike() function (inside drawToSave() ) 我已经通过将此零件移到loadImagesMike()函数的内部(在drawToSave()内 )解决了这个问题。

THIS PART----> 本部分---->

        var myDataURL = canvas.toDataURL(); 
    $.ajax({
      type: "POST",
      url: "/savewearingimg/",
      data: {
         'csrfmiddlewaretoken': "{{ csrf_token }}",
         'imgBase64': myDataURL,
         'singleItemNames': alreadyPutName,//array storing what users have added to the canvas
         'saveWearingName':$('#saveWearingName').val(), //end-users can customized his/her desired wearing title
         'positionsX':positionsX, //position array storing every clothing pictures
         'positionsY':positionsY,
         'sizes':sizes,
      },

    }).done(function(o) {
        alert('saved');
      console.log('saved');

    });/*end ajax*/

THIS PART is moved after the for loop, and it is inside the loadImagesMike() function. 该部分在for循环之后移动,并且位于loadImagesMike()函数内部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM