php本地预览图片,js本地预览图片转base64+php存储成图片

这段代码展示了如何利用JavaScript处理文件上传,将图片转换为Base64编码,并通过AJAX提交到PHP服务器进行保存。在浏览器环境中,它会根据不同的浏览器类型选择合适的方法获取文件URL,然后调用`convertImgToBase64`函数将图片转换为Base64。当用户点击按钮时,将Base64编码的图片数据存储在隐藏字段,并提交表单。
摘要由CSDN通过智能技术生成

functiongetFileUrl(sourceId) {

varurl;

if(navigator.userAgent.indexOf("MSIE")>=1) { // IEurl= document.getElementById(sourceId).value;

} else if(navigator.userAgent.indexOf("Firefox")>0) { // Firefoxurl= window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));

} else if(navigator.userAgent.indexOf("Chrome")>0) { // Chromeurl= window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));

}

returnurl;

}

functionconvertImgToBase64(url, callback, outputFormat){

varcanvas= document.createElement('CANVAS'),

ctx= canvas.getContext('2d'),

img= newImage;

img.crossOrigin = 'Anonymous';

img.onload = function(){

canvas.height= img.height;

canvas.width= img.width;

ctx.drawImage(img,0,0);

vardataURL= canvas.toDataURL(outputFormat || 'image/png');

callback.call(this, dataURL);

canvas= null;

};

img.src = url;

}

/*convertImgToBase64('http://bit.ly/18g0VNp', function(base64Img){// Base64DataURL});*/

(function() {

document.querySelector("#myfile").οnchange= function(){

console.log(this.value);

document.querySelector("#myimg").src= getFileUrl(this.id);

};

document.querySelector("#st").οnclick= function(){

varfsrc;

fsrc= getFileUrl("myfile");

convertImgToBase64(fsrc, function(base64Img){

console.log('11111111111111111');

//console.log(base64Img);// Base64DataURLdocument.querySelector("#myhidden").value= base64Img;

document.querySelector("#myform").submit();

});

};

}

)();

上面代码中现在看来没什么难点,有疑问请看我上一篇文章 js本地预览图片和转base64接下来我们开始创建php文件

saveimg.php:

$img = $_POST['myhidden'];

//匹配出图片的格式

if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img, $result)){

$type = $result[2];

$new_file = "./tesstimg/";

if(!file_exists($new_file))

{

//检查是否有该文件夹,如果没有就创建,并给予最高权限

mkdir($new_file, 0700);

}

$new_file = $new_file.time().".{$type}";

if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img)))){

echo '新文件保存成功:', $new_file;

}else{

echo '新文件保存失败';

}

}

?>

<?=%24img?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值