最近一个项目可能要用到,先把代码实现了再说
avatar.htm
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>头像裁剪</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.css" rel="stylesheet">
<style>
body {
font-family: Arial, sans-serif;
max-width: 500px;
margin: 0 auto;
padding: 20px;
}
.avatar-container {
width: 300px;
height: 300px;
margin: 0 auto 20px;
}
#avatar {
max-width: 100%;
}
.btn {
display: inline-block;
padding: 8px 15px;
background: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
margin-right: 10px;
}
#upload {
display: none;
}
.upload-label {
display: inline-block;
padding: 8px 15px;
background: #2196F3;
color: white;
border-radius: 4px;
cursor: pointer;
}
</style>
</head>
<body>
<h2>头像裁剪</h2>
<div class="avatar-container">
<img id="avatar" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=" alt="Avatar">
</div>
<label for="upload" class="upload-label">选择图片</label>
<input type="file" id="upload" accept="image/*">
<button id="crop-btn" class="btn">裁剪并保存</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.js"></script>
<script>
$(function() {
let cropper;
const $avatar = $('#avatar');
$('#upload').on('change', function(e) {
const files = e.target.files;
if (files.length === 0) return;
const file = files[0];
if (!file.type.match('image.*')) {
alert('请选择图片文件');
return;
}
const reader = new FileReader();
reader.onload = function(event) {
$avatar.attr('src', event.target.result);
if (cropper) {
cropper.destroy();
}
cropper = new Cropper($avatar[0], {
aspectRatio: 1,
viewMode: 1,
autoCropArea: 0.8,
responsive: true
});
};
reader.readAsDataURL(file);
});
$('#crop-btn').on('click', function() {
if (!cropper) {
alert('请先选择图片');
return;
}
const canvas = cropper.getCroppedCanvas({
width: 200,
height: 200,
minWidth: 64,
minHeight: 64,
fillColor: '#fff'
});
if (!canvas) {
alert('裁剪失败,请重试');
return;
}
// 转换为Blob对象
canvas.toBlob(function(blob) {
// 这里可以上传到服务器
const formData = new FormData();
formData.append('avatar', blob, 'avatar.jpg'); //参数 blob:这是要上传的文件数据,这里是裁剪后的图片 Blob 对象,全称为二进制大对象。它是处理文件、图片等二进制数据的核心接口
// 添加其他参数(如用户ID)
formData.append('user_id', 12345); // 数字
formData.append('username', 'john_doe'); // 字符串
// 模拟上传
console.log('准备上传:', blob);
/**/
$.ajax({
url: 'avatar.php',
method: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(response) {
alert('上传成功');
},
error: function() {
alert('上传失败');
}
});
// 显示预览
const url = URL.createObjectURL(blob);
const preview = new Image();
preview.src = url;
preview.style.width = '100px';
preview.style.height = '100px';
preview.style.margin = '10px';
document.body.appendChild(preview);
}, 'image/jpeg', 0.9);
});
});
</script>
</body>
</html>
avatar.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['avatar'])) {
$uploadDir = 'avatar/';
// $filename = uniqid() . '.jpg'; //uniqid()函数用于生成基于当前时间微秒数的唯一标识符,常用于会话ID、文件命名等场景
$filename = $_REQUEST["user_id"]. '.jpg';
$filepath = $uploadDir . $filename;
if (move_uploaded_file($_FILES['avatar']['tmp_name'], $filepath)) {
echo json_encode(['success' => true, 'url' => $filepath]);
} else {
echo json_encode(['success' => false, 'error' => '上传失败']);
}
exit;
}
?>