2017-10-30 8 views
0

두 가지 주요 질문이 있습니다. 나는 데이터없이,javascript 캔버스에서 base64 크기 조정 이미지를 가져올 수 없습니다.

JavaScript reduce the size and quality of image with based64 encoded code

이 내가 그 함수 만 base64로 문자열을 얻을 필요가 있다는 사실을 제외하고, 충분히 간단 보였다

에 대한 대답에 따라 base64로 이미지 크기를 조정하기 위해 노력하고있어 : 이미지를 ... 머리글. base64로 문자열을 반환

function resizeBase64Img(base64, width, height) { 
    var canvas = document.createElement("canvas"); 
    canvas.width = width; 
    canvas.height = height; 
    var context = canvas.getContext("2d"); 
    var deferred = $.Deferred(); 
    $("<img/>").attr("src", "data:image/gif;base64," + base64).load(function() { 
     context.scale(width/this.width, height/this.height); 
     context.drawImage(this, 0, 0); 
     deferred.resolve($("<img/>").attr("src", canvas.toDataURL())); 
    }); 
    var result = canvas.toDataURL(); 
    return result.substr(result.indexOf(",") + 1) 
} 

:

는이 같은 기능을 수정했습니다. 이 문자열은 손상되어 올바르게 표시되지 않습니다. 왜 이런 일이 일어나고 어떻게 해결할 수 있습니까?

다른 질문은 픽셀 크기가 아니라 백분율을 기준으로 이미지의 크기를 조정할 수있는 방법이 있습니까?

감사합니다.

+0

가 고장 todataUrl 전에 이미지를 그려야합니다. – Kaiido

+0

작동하려면 함수를 어떻게 실행해야합니까? – user134167

답변

0

필자가 발견 한 다른 캔버스 기능을 기반으로 함수를 다시 작성했습니다. 이 기능은 크기를 수정, base64로의 IMG의 SRC를 받아 다른 구성 요소에 base64로 결과를 할당합니다

function resizeBase64Img(url, width, height) { 
    var img = new Image(); 
    img.setAttribute('crossOrigin', 'anonymous'); 
    img.onload = function() { 
     var canvas = document.createElement("canvas"); 
     canvas.width = width; 
     canvas.height = height; 
     var ctx = canvas.getContext("2d"); 
     ctx.scale(width/this.width, height/this.height); 
     ctx.drawImage(this, 0, 0); 
     result=canvas.toDataURL(); 
     $('#ASSIGNEDELEMENT').val(result.substr(result.indexOf(",") + 1));  
    }; 

    img.src = url; 
} 

그리고 다음과 같이 호출한다 : 전화 becaise

  resizeBase64Img($('#image').attr('src'),300,300);