base64编码转换成图片,php程序,帮我写一个
时间: 2023-10-20 22:05:20 浏览: 50
当然可以,以下是一个简单的 PHP 程序,可以把 base64 编码的图片转换成 PNG 格式的图片并存储到服务器上:
```php
<?php
// 获取 base64 编码的数据
$data = $_POST['base64data'];
// 去掉数据头部,只保留具体数据
$data = substr($data, strpos($data, ',') + 1);
// 解码 base64 数据
$fileData = base64_decode($data);
// 生成文件名
$filename = uniqid() . '.png';
// 保存文件到服务器
file_put_contents($filename, $fileData);
?>
```
在客户端的 HTML 代码中,需要将 base64 编码的数据传递给服务器,例如:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>上传图片</title>
</head>
<body>
<input type="file" id="file" onchange="upload()">
<script>
function upload() {
var file = document.getElementById("file").files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
var data = e.target.result;
var xhr = new XMLHttpRequest();
xhr.open('POST', '/save-image.php', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send('base64data=' + data);
};
}
</script>
</body>
</html>
```
请注意,为了安全起见,请不要直接将 base64 编码的数据传递给服务器,而应该使用 POST 方法进行传递。如果您还需要更多关于 PHP 和图片处理的信息,请查看 CSDN 的相关文章。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)