如何从base64数据字符串中保存PNG图片在服务器端 [英] How to save a PNG image server-side, from a base64 data string javascript

查看:478
本文介绍了如何从base64数据字符串中保存PNG图片在服务器端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码,或者ajax无法正确传输数据,或者我的php无法正常工作.我知道画布正在保存到写入页面的数据png中.有没有一种方法可以将其转换为文件并从javascript保存?

i have this code, either the ajax isn't transferring the data correctly or my php doesn't work properly. i know the canvass is saving to data png it writes to the page. Is there a way to just convert it to a file and save it from javascript?

启动JAVASCRIPT:-------------------

START JAVASCRIPT:-------------------

<--获取canvas元素并将其转换为数据png->

<-- get the canvass element and convert to data png -->

var canvas = document.getElementById("textCanvas"); 
var img = canvas.toDataURL("image/png");

<-结束canvas元素并转换为数据png->

<-- END the canvass element and convert to data png -->

<-发送到php文件->

<-- SEND to php file -->

var onmg = encodeURIComponent(img);
var xhr = new XMLHttpRequest();
var body = "img=" + onmg;
xhr.open('POST', "convertit.php",true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-Length", body.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(body);
xhr.onreadystatechange = function () {
   if (xhr.status == 200 && xhr.readyState == 4) {
     document.getElementById("div").innerHTML = xhr.responseText;
   } else {
     document.getElementById("div").innerHTML = 'loading';
     }
   }

<-END发送到php文件->

<-- END send to php file -->

END JAVASCRIPT:-------------------

END JAVASCRIPT:-------------------

启动PHP:-------------------

START PHP:-------------------

$img = $_POST['img']; 
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
file_put_contents('/uploads/file.png', $data);

END PHP:-------------------

END PHP:-------------------

推荐答案

将php更改为-------->

changed the php to -------->

define('UPLOAD_DIR', 'images/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . 'txtimg.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';

我从----->获得的

http://j-query.blogspot.com/2011/02/save-base64-encoded-canvas-image-to-png.html

which i got from ----->http://j-query.blogspot.com/2011/02/save-base64-encoded-canvas-image-to-png.html

-欢呼棒极了:)

这篇关于如何从base64数据字符串中保存PNG图片在服务器端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆