Skip to content Skip to sidebar Skip to footer

BLOB URL To File With PHP

I'm trying to create a file preview system. When the user click in a upload button and select files, I use the HTML5 FILE API to get all the file info and create a thumbnail for th

Solution 1:

well, I keep looking for solutions and I found this one: Canvas.

Canvas element have the toDataUrl() method that returns a Data URL for the image that it contains.

So I keep doing the same thing but when I submit the form I use the following function:

function putImage(){
    var url = document.getElementById("img1").src; // 'img1' is the thumbnail - I had to put an id on it
    var canvas = document.getElementById("MyCanvas");
    if (canvas.getContext) {
        var ctx = canvas.getContext("2d");

        var img = new Image();
        img.src = url;
        img.onload = function () {
            // Desenha a imagem no canvas...
            ctx.drawImage(img,0,0);

            // Grava o Data URL na imagem...
            var myImage = canvas.toDataURL("image/png");
            document.getElementById("dataurl").value = myImage;
        }
    }
};

I create one more element on the page for canvas:

<canvas id="MyCanvas">This browser or document mode doesn't support canvas</canvas>

and one more element on the form to save the Data URL:

<input id="dataurl" name="dataurl" type="text" size="50" />

well, now I can get it all in PHP and do something like this:

if($_POST)
{
    //echo '<pre>'; print_r($_POST); echo '</pre>';

    $blob = $_POST['bloburl'];
    $type = $_POST['blobtype'];
    $data = $_POST['dataurl'];

    $contents_split = explode(',', $data);
    $encoded = $contents_split[count($contents_split)-1];
    $decoded = "";
    for ($i=0; $i < ceil(strlen($encoded)/256); $i++) {
        $decoded = $decoded . base64_decode(substr($encoded,$i*256,256)); 
    }

    $fp = fopen('imagembaixada.jpg', 'w');
        fwrite($fp, $decoded);
        fclose($fp);
    }
}

Now my image is saved.

It works, but looks pretty inefficient.

If someone knows a better way to create a preview for images before upload them, please tell me!


Post a Comment for "BLOB URL To File With PHP"