dataurl to image for download in php

蹲街弑〆低调 提交于 2019-12-09 22:22:00

问题


I'm creating image using canvas and using following script,

function getImage() {
    var canvas1 = document.getElementById("images");

    if (canvas1.getContext) {
        var ctx = canvas1.getContext("2d");
        var myImage = canvas1.toDataURL("image/jpg");
    }
    $('<form action="download.php" method="POST">' + 
    '<input type="hidden" name="aid" value="' + myImage + '">' +
    '</form>').submit();

}

And in my Download.php file is,

<?php $img = $_POST['aid']; 
    echo "<img src=".$img.">";
?>

it showing image correctly. But i wanna give download button with jpg format or pdf format.

How i can use?

I used base64_decode(); method. But i cant solve.

Help me...


回答1:


Thanks for all. but I got answer using,

file_put_contents();

But thing, i dont know how to use. Finally i got it from this Answer.

Answer is,

$data = 'data:image/png;base64,AAAFBfj42Pj4';

list($type, $data) = explode(';', $data);
list(, $data)      = explode(',', $data);
$data = base64_decode($data);

file_put_contents('/tmp/image.png', $data);

But still i'm waiting for download button with option of image/pdf format.




回答2:


Try this:

PHP echo'ed image with link

<?php

$img = $_POST['aid'];
echo "<a href='download_image.php'><img src=".$img."></a>";

?>

download_image.php

<?php

$img = "myimage.jpg";

// fix for IE catching or PHP bug issue
header("Pragma: public");
header("Expires: 0"); // set expiration time
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
// browser must download file from server instead of cache

// force download dialog
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");

// use the Content-Disposition header to supply a recommended filename and 
// force the browser to display the save dialog. 
header("Content-Disposition: attachment; filename=".basename($img).";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($img));

readfile("$img");
exit();

?>


来源:https://stackoverflow.com/questions/18230573/dataurl-to-image-for-download-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!