js图片截取(类似微信头像截取)

2021-10-30

使用jquery的Jcrop插件,地址:http://code.ciaoca.com/jquery/jcrop/

html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图片截取</title>
    <link rel="stylesheet" href="http://cdn.bootcdn.net/ajax/libs/jquery-jcrop/0.9.15/css/jquery.Jcrop.css">
    <style>
        .details-left-operate input{
            padding: 0;
        }
    </style>
</head>
<body>
<div class="add-box">
    <form method="post" id="form" class="layui-form">
        <div class="form-item">
             <p>
                 请上传2M以内的图片
             </p>
             <p>
                 请在上传图片后截取签字信息
             </p>
             <p class="preview-container" style="width: 409px;height: 212px;overflow: hidden;">
                 <img src="" class="jcrop-preview">
             </p>
             <p>
                 <input name='file' type="file" id="fileUp" />
                 <span><img src="" alt="" id="img1"></span>
             </p> 
        </div>
        <div class="form-btn details-left-operate">
            <input class="g-jcys" type="button" value="确定"  id="nextBtn">
        </div>
    </form>
</div>
</body>
</html>

js代码

<script type="text/javascript" src="http://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.bootcdn.net/ajax/libs/jquery-jcrop/0.9.15/js/jquery.Jcrop.min.js"></script>

<script>
    var file,boundx,boundy;
    $('#fileUp').on('change', function(e) {
        if (!$(this).val()) {
            return false;
        }
        file = e.currentTarget;
        var filePath = $(this).val(),
        fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase(),
        src = window.URL.createObjectURL(this.files[0]);

        // 检查是否是图片
        if(!fileFormat.match(/.png|.jpg|.jpeg/)) {
            layer.msg("请上传png/jpg/jpeg格式图片");
            return;
        }else{
            $("#img1").remove();
            $("#fileUp").next("span").append('<img src="" alt="" id="img1">');
            
            if (jcrop_api) {
                jcrop_api.destroy();
            }
            $('#img1').attr('src', src); 
            $('.jcrop-preview').attr('src', src); 
            $('#img1').Jcrop({
                onSelect: updatePreview,
                setSelect: [0, 0, 409, 212],
                aspectRatio: 409 / 212,
            },function(){
                var bounds = this.getBounds();
                boundx = bounds[0];
                boundy = bounds[1];
                jcrop_api = this;
            });  
        } 
    });
    var jcrop_api, img = {};
    function updatePreview(c)
    {
        img = {
            x: c.x,
            y: c.y,
            w: c.w,
            h: c.h, 
        }
        if (parseInt(c.w) > 0) {
            var rx = 409 / c.w; // 预览位置宽与实际选择图片宽的比例
            var ry = 212 / c.h; // 预览位置高与实际选择图片高的比例
            
            $(".jcrop-preview").css({
                width: Math.round(rx * boundx) + 'px',
                height: Math.round(ry * boundy) + 'px',
                marginLeft: '-' + Math.round(rx * c.x) + 'px',
                marginTop: '-' + Math.round(ry * c.y) + 'px'
            });
        }
    }

    $("#nextBtn").click(function(){
        var formData = new FormData();
        formData.append('file', file.files[0]);
        formData.append('img_x', img.x);
        formData.append('img_y', img.y);
        formData.append('img_w', img.w);
        formData.append('img_h', img.h);
        $.ajax({
            url: "upload.php",
            type: 'POST',
            dataType: 'json',
            data: formData,
            contentType: false,
            processData: false
        })
        .done(data => {
            if (data.code == 1) {
                parent.$('#img').attr("src", data.data)
                parent.$('#signature').val(data.data)
                parent.layer.closeAll();
            } else {
                layer.msg(data.data);
            }
        })
        .fail(data => {
            console.log(data);
        });
    })
</script>

php代码

function upload()
{
    $ext  = explode('.', $_FILES['file']['name'])[1];
    $path = './public/' . bin2hex(random_bytes(8)) . '.' . $ext;
    move_uploaded_file($_FILES['file']['tmp_name'], $path);
    $image   = imagecreatefromstring(file_get_contents($path));
    $new_img = imagecreatetruecolor(409, 212);
    // 从原始图片$image的起始坐标$_POST['img_x'],$_POST['img_y'],截取宽高$_POST['img_w'],$_POST['img_h'],复制到图片$new_img上,从0,0开始复制,复制后的宽高为409,212
    imagecopyresampled($new_img, $image, 0, 0, $_POST['img_x'], $_POST['img_y'], 409, 212, $_POST['img_w'], $_POST['img_h']);
    imagedestroy($image);
    @unlink($path);
    $path = './public/' . bin2hex(random_bytes(8)) . '.' . $ext;
    imagejpeg($new_img, $path);
    imagedestroy($new_img);
    return $path;
}

 

{/if}