3

I have recently written a script to upload images. Everything works well. But now I want to resize the image after uploading it. I have done some research on it and I want to try it with the <canvas> element. I have parts of the script, others are missing and I don't know how to connect everything.

These are the steps:

  1. Upload the image into img/uploads - Done.

    <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. Put the image into a canvas element - Missing

  3. Resize it - Part of the code I want to use somehow:

    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. Replace the existing image with the new resized one. - Missing

It would be very nice if someone would give me some tips to complete it - Thank you!

Dan Green
  • 45
  • 4

2 Answers2

4

(#2-3) Resizing the source image onto a canvas

  • Calculate the scaling factor required to fit MAX dimensions without overflow
  • Create a new canvas with the scaled dimensions
  • Scale the original image and draw it onto the canvas

Important! Be sure the source image is coming from the same domain as your web page or else toDataURL will fail for security reasons.

(#4) You can convert the canvas from #3 to an image with resizedImg.src=context.toDataURL

Example annotated code and a Demo:

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;}
markE
  • 94,798
  • 10
  • 135
  • 158
  • thanks a lot! Is there any way to save this new image automatically to the server? – Dan Green Jul 29 '16 at 19:36
  • "Automatically" -- no. But you can use AJAX to upload the resized dataURL (not the imageObject!). Many posts showing "how-to" ... [Here's one of them](http://stackoverflow.com/questions/18736023/cannot-send-canvas-data-from-javascript-ajax-to-php-page/18747480#18747480). Good luck with your project! :-) – markE Jul 29 '16 at 19:42
1

I would recommend using ajax for upload, since when you upload you redirect to the php page. But the example I didn't use it either

References:

    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

Here is what I have for 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>

For PHP I used a different way for file upload (for instance I store the picture in 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>")

?>
Sen Qiao
  • 126
  • 1
  • 5