Skip to content Skip to sidebar Skip to footer

Append Canvas Images To Input Array With Javascript

I am trying to get work my code, but I have not been successful. Basically what I want is to apply a resize algorithm to multiple images selected by the user, making them in HTML5

Solution 1:

EDIT: Updated comments in answer and updated code.

There were a number of things that stopped your code from working, alas I'm tired and forgot to make note of them as I went and have forgotten the specifics. :(

You may wish to review the following code.

It loads the images using a fileReader and the method .readAsDataURL. This then fires a user-supplied callback on completion. This callback method then attempts to load the dataURL as an image. When (if!) this succeeds, the image is drawn onto a scaled canvas and then the dataURL of that canvas is retrieved. This dataURL is added to an array and the number of scaled images is compared to the number of selected images. When the two numbers match, it JSON encodes the array and stuffs it into the hidden input, before submitting the form.

On the php side, we get the submitted data and JSON decode it. We then display a count of the number of images in this array, before ouputing each element as the src of an image,to confirm successful upload.

I've added code that will ensure the chosed file is an image before processing it any further. You can select a mixed list of files and only the images will be processed. I don't handle the case when the chosen file is an image yet trying to load it into an img element fails.

resizeAndUpload.html

<html><head><script>functionnewEl(tagName){returndocument.createElement(tagName);}

var nFiles, nSized, nPics, mPicArray;

functionmyResizeAll()
{
    nFiles = pictures.files.length;
    nSized = 0;
    nPics = 0;
    mPicArray = [];

    // work out how many of the chosen files are imagesfor (var i=0; i<nFiles; i++)
    {
        if (pictures.files[i].type.indexOf("image") != -1)
            nPics++;
    }

    // now try to load the ones that are imagesfor (var i=0; i<nFiles; i++)
    {
        if (pictures.files[i].type.indexOf("image") != -1)
            loadFileObject( pictures.files[i], onFileDataLoaded );
    }
}

// callback gets data via the .target.result field of the param passed to it.functionloadFileObject(fileObj, loadedCallback)
{
    var reader = newFileReader();
    reader.onload = loadedCallback;
    reader.readAsDataURL( fileObj );
}

functiononFileDataLoaded(e)
{
    var tmpImg = newEl('img');
    tmpImg.addEventListener('load', onImgElemLoaded, false);
    tmpImg.src = e.target.result;
}

functiononImgElemLoaded(evt)
{
    // create a canvasvar can = newEl('canvas');
    var ctx = can.getContext('2d');

    // scale itvar scale = 0.5;
    can.width = this.width * scale;
    can.height = this.height * scale;

    // draw scaled image
    ctx.drawImage(this, 0, 0, can.width, can.height);

    // get dataURLvar resizedImgDataURL = can.toDataURL();
    mPicArray.push( resizedImgDataURL );

    nSized++;

    // when all image files have been loaded, then loaded as image elements and finally resized on a canvas,// submit the data.if (nSized == nPics)
    {
        document.getElementById("sizedpics").value= JSON.stringify(mPicArray);
        document.forms["frm"].submit();
    }
}
</script></head><body><inputtype="file"id="pictures"multiple><br><formid="frm"action="save.php"method="POST"><inputtype="hidden"name='sizedpics'id="sizedpics"/><buttontype="button"onclick="myResizeAll()">submit!</button></form><canvasid="canvas"style='display:none'width="800"></canvas><br></body></html>

save.php

<?php$imgArray = json_decode( $_POST['sizedpics'] );

    print_r( count($imgArray) );

    $numPics = count($imgArray);
    for ($i=0; $i<$numPics; $i++)
    {
        printf("<img src='%s'/>\n", $imgArray[$i]);
    }
?>

Output

enter image description here

Your English is just fine.It's better than that of many native-speakers. ;)

Post a Comment for "Append Canvas Images To Input Array With Javascript"