帮我写一个直接可用的图片在线压缩网页源码并且用CSS美化一下
以下是一个简单的图片在线压缩网页源码,并使用CSS进行美化:
<!DOCTYPE html>
<html>
<head>
<title>图片在线压缩</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
background-color: #f5f5f5;
}
h1 {
text-align: center;
color: #333333;
}
.container {
max-width: 400px;
margin: 0 auto;
background-color: #ffffff;
padding: 20px;
border: 1px solid #dddddd;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 5px;
color: #333333;
}
input[type="file"] {
display: block;
margin-top: 5px;
}
button {
padding: 10px 20px;
background-color: #333333;
color: #ffffff;
border: none;
cursor: pointer;
}
.compressed-image {
margin-top: 20px;
text-align: center;
}
.compressed-image img {
max-width: 100%;
}
</style>
</head>
<body>
<h1>图片在线压缩</h1>
<div class="container">
<form id="compress-form" enctype="multipart/form-data">
<div class="form-group">
<label for="image-input">选择要压缩的图片:</label>
<input type="file" id="image-input" accept="image/*" required>
</div>
<button type="submit">压缩图片</button>
</form>
<div class="compressed-image" id="compressed-image-container"></div>
</div>
<script>
document.getElementById('compress-form').addEventListener('submit', function(e) {
e.preventDefault();
var fileInput = document.getElementById('image-input');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('image', file);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/compress-image', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
var compressedImageContainer = document.getElementById('compressed-image-container');
compressedImageContainer.innerHTML = '<img src="' + xhr.responseText + '">';
}
};
xhr.send(formData);
});
</script>
</body>
</html>
请注意,上述代码中的压缩图片的功能需要服务器端支持。在这个例子中,我们将压缩图片的逻辑放在了/compress-image的URL上。你需要自行在服务器端实现这个逻辑,并返回压缩后的图片URL
原文地址: https://www.cveoy.top/t/topic/itX2 著作权归作者所有。请勿转载和采集!