我正在做一个小项目, 我需要在其中生成 QR 代码和标识。 我需要以 PNG 或 JPEG 格式保存生成的 QR 代码。 如果我使用 svg 格式, 下面的代码运行正常 。 但我想要将文件保存为 PNG 或 JPEG 格式 。 我试图将 svg 替换为 png, 它保存文件, 但我无法打开它。 当我尝试打开 PNG 文件时, 它会表示不支持的格式 。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>QR Code Styling</title>
<script type="text/javascript" src="https://unpkg.com/[email protected]/lib/qr-code-styling.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<div id="canvas"></div>
<script type="text/javascript">
const qrCode = new QRCodeStyling({
width: 300,
height: 300,
type: "svg",
data: "https://www.facebook.com/",
image: "https://upload.wikimedia.org/wikipedia/commons/5/51/Facebook_f_logo_%282019%29.svg",
dotsOptions: {
color: "#4267b2",
type: "rounded"
},
backgroundOptions: {
color: "#e9ebee",
},
imageOptions: {
crossOrigin: "anonymous",
margin: 20
}
});
var svgBlob = qrCode.getRawData( jpeg );
svgBlob.then(value => value.text().then(value => sendAjax(value)));
function sendAjax(svgString) {
$.ajax( 保存qr.php , {
data : svgString, //canvas.innerHTML,
type : POST ,
processData : false,
contentType : image/jpg
});
}
qrCode.append(document.getElementById("canvas"));
// qrCode.download({ name: "qr", extension: "svg" });
</script>
</body>
</html>
保存qr.php
<?php
$svg = file_get_contents( php://input );
$myfile = fopen("testfile.jpeg", "w");
fwrite($myfile, $svg);
?>