如何从dataurl在服务器上创建映像文件

时间:2013-03-28 05:47:58

标签: javascript image data-url

我有一个dataurl格式的图像,如:

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

我需要将JavaScript中的这个字符串转换为另一个字符串,该字符串可以直接复制到空白的jpg文件中,以便用户可以查看。 知道如何实现这个目标吗?

4 个答案:

答案 0 :(得分:2)

如果您希望用户能够下载文件并将其保存在计算机上的某个位置,请尝试以下操作:

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

如果您正在尝试这样做,请参阅Download data url file

答案 1 :(得分:1)

您只需从DataURI中删除“data:image / jpeg; base64”。

$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 :(得分:0)

要显示它,您可以使用src属性:

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

要生成文件,您需要使用canvas元素:

示例:

<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>

并保存图像和内容......您可以找到一种方法将画布转换为此链接中的文件:

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

编辑:新链接,我猜...... https://github.com/hongru/canvas2image

答案 3 :(得分:0)

您必须从data:image/jpeg;base64,中删除dataURI并解码dataURI

public void saveImage(String imageURI) {
    BufferedImage image = null;
    String blobString=imageString.replace("data:image/jpeg;base64,", "");
    byte[] byteArray = Base64.getDecoder().decode(blobString);
    ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);
    try {
        image = ImageIO.read(bis);
        File file = new File("/home/rakesh/Vinay/a.jpeg");
        ImageIO.write(image, "jpeg", file);
    } catch (IOException e) {
        e.printStackTrace();
    }
}