简介

客户端实现

1. 选择合适的图片上传插件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图片上传</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://github.com/swfupload/uploadify/releases/v3.2.1/uploadify.css">
    <script src="https://github.com/swfupload/uploadify/releases/v3.2.1/jquery.uploadify.min.js"></script>
</head>
<body>
    <input type="file" id="file" name="file" />
</body>
</html>

2. 配置uploadify插件

uploadify插件中,我们需要设置上传的URL、文件类型等参数。

$(document).ready(function() {
    $('#file').uploadify({
        'swf'      : 'uploadify.swf',
        'uploader' : 'upload.php',
        'buttonImage' : 'upload-btn.png',
        'fileTypeExts' : '*.jpg;*.png;*.gif',
        'onUploadSuccess' : function(file, data, response) {
            alert('The file ' + file.name + ' was uploaded successfully.');
        }
    });
});

服务器端实现

1. PHP处理上传的图片

<?php
if (isset($_FILES['file'])) {
    $file = $_FILES['file'];
    $uploadPath = 'uploads/';
    $filename = $uploadPath . basename($file['name']);
    move_uploaded_file($file['tmp_name'], $filename);
}
?>

2. 使用GD库裁剪图片

<?php
function cropImage($imagePath, $newWidth, $newHeight) {
    list($width, $height) = getimagesize($imagePath);
    $image = imagecreatefromjpeg($imagePath);
    $cropX = ($width - $newWidth) / 2;
    $cropY = ($height - $newHeight) / 2;
    $croppedImage = imagecreatetruecolor($newWidth, $newHeight);
    imagecopyresampled($croppedImage, $image, 0, 0, $cropX, $cropY, $newWidth, $newHeight, $newWidth, $newHeight);
    imagejpeg($croppedImage, 'cropped_' . basename($imagePath));
    imagedestroy($image);
    imagedestroy($croppedImage);
}
?>

在线裁剪

1. 使用jCrop插件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>在线裁剪</title>
    <link rel="stylesheet" href="https://github.com/tapmodo/jCrop/releases/v0.9.12/css/jquery.Jcrop.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://github.com/tapmodo/jCrop/releases/v0.9.12/js/jquery.Jcrop.min.js"></script>
</head>
<body>
    <img id="cropbox" src="path/to/image.jpg" alt="Image" />
    <button id="crop">裁剪</button>
</body>
</html>

2. 客户端处理裁剪区域

在客户端,我们需要使用jCrop插件来处理裁剪区域。

$(document).ready(function() {
    $('#cropbox').Jcrop({
        onChange: updatePreview,
        onSelect: updatePreview
    });

    function updatePreview(c) {
        if (parseInt(c.w) > 0) {
            $('#x').val(c.x);
            $('#y').val(c.y);
            $('#w').val(c.w);
            $('#h').val(c.h);
        }
    }
});

3. 服务器端处理裁剪请求

<?php
if (isset($_POST['x']) && isset($_POST['y']) && isset($_POST['w']) && isset($_POST['h'])) {
    $x = $_POST['x'];
    $y = $_POST['y'];
    $w = $_POST['w'];
    $h = $_POST['h'];
    $imagePath = 'path/to/image.jpg';
    $croppedImagePath = 'path/to/cropped_image.jpg';
    cropImage($imagePath, $w, $h);
}
?>

总结