Maison  >  Article  >  développement back-end  >  html上传图片数据到服务器,php接收保存图片

html上传图片数据到服务器,php接收保存图片

WBOY
WBOYoriginal
2016-08-08 09:26:351541parcourir




很多时候,我们需要把web端的图片数据或者canvas里面的画面保存到服务器上。html5已经提供了可用的接口。


Canvas的toDataURL方法,可以将canvas上的画布数据导出成字符串格式。我们只需要再把字符串传输给服务器就可以了。

如果图片是img标签的,怎么办呢?

很简单,canvas提供了drawImage方法,用于把img或者其他canvas的数据画到自己的画布上。

下面,我们看看客户端的代码:

var cc = window.document.getElementById("egretCanvas");
var cc2 = document.createElement("canvas");
cc2.setAttribute("width", "320");
cc2.setAttribute("height", "514");
var ctx = cc2.getContext("2d");
ctx.drawImage(cc, 0, 0, 320, 514);
var imgdata: string = cc2["toDataURL"]();


这样导出后的字符串,含有前缀“data:image/png;base64,”,所以我们需要把这个前缀去掉

imgdata = imgdata.substring(22); 

然后把字符串传给服务器,这里我们选择使用php语言来接收数据并保存图片。


$imgurl = str_replace(' ', '+', $_REQUEST['image']);
先把字符串中的空格替换成"+"号。


$savePath = "../images/123.png";
$image = base64_decode($image);
file_put_contents($savePath,$image);

php拿到数据后,需要进行base64解码,才能保存成图片。



以上就介绍了html上传图片数据到服务器,php接收保存图片,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn