how to create an image file on server from dataurl

女生的网名这么多〃 提交于 2019-12-05 09:04:31

问题


I have an image in a dataurl format, like:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwME…iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/2Q== 

I need to convert this string in JavaScript to another string which can be directly copied to a blank jpg file so that it can be viewed by the user.
Any idea how to achieve this?


回答1:


You just need to remove "data:image/jpeg;base64," from DataURI.

$dataUri = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgM...";
// remove "data:image/jpeg;base64," from image Data URI.
$data = str_replace("data:image/jpeg;base64,", "", $dataUri);

// save to file
file_put_contents("/tmp/image.jpeg", base64_decode($data));



回答2:


If you want the user to be be able to download the file and save it somewhere on their computer, try this:

document.location.href = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQAB…";

See Download data url file if this is what you're trying to do.




回答3:


To display it you can use the src attribute:

<img src="data:image/png;base64,R0lGODlhUAAPAKIAAA+g4JADs=" width="80" height="80" />

To generate a file you need use canvas element:

Example:

<html>
    <head></head>
    <body>
        <canvas id="c"></canvas>
        <script type="text/javascript" src="canvas2image.js"></script>
        <script type="text/javascript" src="baseg4.js"></script>
        <script type="text/javascript">

            var canvas = document.getElementById("c");
            var ctx = canvas.getContext("2d");

            var image = new Image();
            image.src = "data:image/png;base64,iVBORw0KG............5CYII%3D";
            image.onload = function()
            {
               ctx.drawImage(image, 0, 0);
                var foo = Canvas2Image.saveAsPNG(canvas);  
            };
            var img = canvas.toDataURL("image/png");
        </script>
    </body>
</html>

And save the image and stuff... you can find a way to convert the canvas to a file in this link:

// http://www.nihilogic.dk/labs/canvas2image/

EDIT: New link, I guess... https://github.com/hongru/canvas2image



来源:https://stackoverflow.com/questions/15675063/how-to-create-an-image-file-on-server-from-dataurl

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