2016-07-29 4 views
1

최근에 이미지를 업로드하기위한 스크립트를 작성했습니다. 모든 것이 잘 작동합니다. 하지만 이제 이미지를 업로드 한 후에 크기를 조정하려고합니다. 몇 가지 연구를 해본 결과 <canvas> 요소로 시험해보고 싶습니다. 나는 스크립트의 일부를 가지고 있으며, 다른 것들은 누락되어 있으며 모든 것을 연결하는 방법을 모른다. 업로드하기 전에 캔버스로 이미지 크기 조정

이 단계는 다음과 같습니다

  1. img/uploads에 이미지를 업로드 - 완료.

    <form action="picupload.php" method="post" enctype="multipart/form-data"> <input name="uploadfile" type="file" accept="image/jpeg, image/png"> <input type="submit" name="btn[upload]"> </form>

    picupload.php : 캔버스 요소에 이미지를 넣어

    $tmp_name = $_FILES['uploadfile']['tmp_name']; $uploaded = is_uploaded_file($tmp_name); $upload_dir = "img/uploads"; $savename = "[several code]";

    if($uploaded == 1) { move_uploaded_file ( $_FILES['uploadfile']['tmp_name'] , "$upload_dir/$savename"); }

  2. -

  3. 은 크기를 조정 누락 - 코드 I의 일부 어떻게 든 사용하고 싶다 :

    var MAX_WIDTH = 400;   
    var MAX_HEIGHT = 300; 
    var width = img.width; 
    var height = img.height; 
    
    if (width > height) { 
        if (width > MAX_WIDTH) { 
         height *= MAX_WIDTH/width; 
         width = MAX_WIDTH; 
        } 
    } else { 
        if (height > MAX_HEIGHT) { 
         width *= MAX_HEIGHT/height; 
         height = MAX_HEIGHT; 
        } 
    } 
    
  4. 기존 이미지를 새 크기 조정 된 이미지로 바꿉니다. - 누락 됨

누군가가 나에게 끝내기위한 몇 가지 팁을 주시면 매우 좋을 것입니다. - 감사합니다!

+1

글쎄, 어떻게 이미지를 업로드하나요? – Adjit

+0

@Adjit 추가했습니다;) –

+0

이미지 잡기 - http://stackoverflow.com/questions/4459379/preview-an-image-before-it-is-uploaded; 캔버스에 이미지를 추가하는 경우 - http://stackoverflow.com/questions/6011378/how-to-add-image-to-canvas – Adjit

답변

2

캔버스

  • 에 원본 이미지 크기 조정 (# 2-3)
  • 가 축소 크기로 새로운 캔버스를 작성 오버 플로우없이 MAX의 크기에 맞도록 필요한 스케일링 계수를 계산
  • 축척 원래 이미지를 캔버스에 그립니다.

중요! 원본 이미지가 웹 페이지와 동일한 도메인에서 왔는지 확인하십시오. 그렇지 않으면 보안상의 이유로 toDataURL이 실패합니다.

당신은 resizedImg.src=context.toDataURL

예 주석 코드와 데모와 이미지에 # 3에서 캔버스를 변환 할 수 있습니다 (4 #) :

var MAX_WIDTH = 400;   
 
var MAX_HEIGHT = 300; 
 

 
var img=new Image(); 
 
img.crossOrigin='anonymous'; 
 
img.onload=start; 
 
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/annotateMe.jpg"; 
 
function start(){ 
 

 
    var canvas=fitImageOntoCanvas(img,MAX_WIDTH,MAX_HEIGHT); 
 

 
    // #4 
 
    // convert the canvas to an img 
 
    var imgResized=new Image(); 
 
    imgResized.onload=function(){ 
 
     // Use the new imgResized as you desire 
 
     // For this demo, just add resized img to page 
 
     document.body.appendChild(imgResized); 
 
    } 
 
    imgResized.src=canvas.toDataURL(); 
 
    
 
} 
 

 
// #3 
 
function fitImageOntoCanvas(img,MAX_WIDTH,MAX_HEIGHT){ 
 

 
    // calculate the scaling factor to resize new image to 
 
    //  fit MAX dimensions without overflow 
 
    var scalingFactor=Math.min((MAX_WIDTH/img.width),(MAX_HEIGHT/img.height)) 
 

 
    // calc the resized img dimensions 
 
    var iw=img.width*scalingFactor; 
 
    var ih=img.height*scalingFactor; 
 

 
    // create a new canvas 
 
    var c=document.createElement('canvas'); 
 
    var ctx=c.getContext('2d'); 
 

 
    // resize the canvas to the new dimensions 
 
    c.width=iw; 
 
    c.height=ih; 
 

 
    // scale & draw the image onto the canvas 
 
    ctx.drawImage(img,0,0,iw,ih); 
 
    
 
    // return the new canvas with the resized image 
 
    return(c); 
 
}
body{ background-color:white; } 
 
img{border:1px solid red;}

+0

감사합니다. 이 새로운 이미지를 자동으로 서버에 저장하는 방법이 있습니까? –

+0

"자동"- 아니요. 그러나 AJAX를 사용하여 크기가 조정 된 dataURL (imageObject가 아님)을 업로드 할 수 있습니다. "방법"을 보여주는 많은 게시물 ... [그들 중 하나가] (http://stackoverflow.com/questions/18736023/cannot-send-canvas-data-from-javascript-ajax-to-php-page/ 18747480 # 18747480). 프로젝트에 행운을 빌어 요! :-) – markE

1

나는 것 PHP 페이지로 리디렉션을 업로드 할 때부터 업로드 용으로 아약스를 사용하는 것이 좋습니다. 그러나 예를 들어 내가 그것을 사용하지 않은 중 하나

참고 :

여기
http://stackoverflow.com/questions/12368910/html-display-image-after-selecting-filename 

    http://stackoverflow.com/questions/4459379/preview-an-image-before-it-is-uploaded 

    http://stackoverflow.com/questions/6011378/how-to-add-image-to-canvas 

    http://stackoverflow.com/questions/331052/how-to-resize-html-canvas-element 

    http://stackoverflow.com/questions/2142535/how-to-clear-the-canvas-for-redrawing 

내가 (에 대한 I는 파일 업로드에 대해 다른 방법을 사용 PHP의 HTML

<!DOCTYPE html> 
<html> 
<head> 
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> 
    <meta charset="utf-8"> 
    <style> 
    </style> 
    <title>Something</title> 
</head> 
<body> 

<form action="picupload.php" method="post" enctype="multipart/form-data"> 
    <input name="uploadfile" type="file" accept="image/jpeg, image/png"> 
    <input type="submit"> 
</form> 

</body> 
<script src="http://code.jquery.com/jquery-latest.min.js" 
     type="text/javascript"></script> 
<script> 


</script> 
</html> 

을 위해 무엇을 가지고 예 : localhost /에 그림을 저장합니다.) :

<?php 

if(isset($_FILES['uploadfile']['name'])){ 
    $nameFile=$_FILES['uploadfile']['name']; 
    $pathFile = "C:/inetpub/wwwroot/" . $_FILES['uploadfile']['name']; 

    $file_tmp2=$_FILES['uploadfile']['tmp_name']; 
    move_uploaded_file($file_tmp2, $pathFile); 
} 


echo (" 

<!DOCTYPE html> 
<html> 

<head> 
    <meta name='viewport' content='initial-scale=1.0, user-scalable=no'> 
    <meta charset='utf-8'> 
    <style> 
    </style> 
    <title>Something</title> 
</head> 
<body> 
<canvas id='viewport' ></canvas> 
<button onclick='change()'>change</button> 
</body> 
<script> 
var canvas = document.getElementById('viewport'), 
context = canvas.getContext('2d'); 

make_base(); 

function make_base() 
{ 
    base_image = new Image(); 
    base_image.src = '").$_FILES['uploadfile']['name']; 
    echo("'; 
    base_image.onload = function(){ 
    context.drawImage(base_image, 100, 100); 
    } 
} 


function change(){ 
    context.clearRect(0, 0, canvas.width, canvas.height); 
    context.drawImage(base_image, 0, 0, 400 ,300); 
} 
</script>") 

?> 
관련 문제