PhotoClip移动端、pc端上传头像裁剪

photoClip是一款支持移动设备触摸手势的图片裁剪jQuery插件。

github地址下载插件:
https://github.com/baijunjie/PhotoClip.js

一般引入

<script src="js/iscroll-zoom.js"></script>
<script src="js/hammer.min.js"></script>
<script src="js/lrz.all.bundle.js"></script>
<script src="js/PhotoClip.js"></script>

html部分

<div id="clipArea">
    <span id="add">+</span>
</div>
<input style="visibility: hidden;" type="file" id="file">

<button id="clipBtn">使用</button>

<?php $form = ActiveForm::begin([
    'options' => ["enctype" => "multipart/form-data", 'id' => 'form']
]) ?>
<?= $form->field($model, 'image')->hiddenInput()->label(false); ?>
<?php ActiveForm::end(); ?>

<?= Alert::widget() ?>

样式部分

<style>
    .alert-danger .close {
        margin-top: 0;
        margin-left: 70%;
    }

    body {
        margin: 0;
        text-align: center;
    }

    #clipArea {
        height: 300px;
        font-size: 100px;
        text-align: center;
        vertical-align: middle;
    }

    #file,
    #clipBtn {
        margin: 20px;
    }

    #add {
        font-size: 100px;
        display: block;
        width: 100px;
        line-height: 100px;
        height: 100px;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -60%);
        z-index: 100;
        -webkit-transform: translate(-50%, -60%);
    }
</style>

js部分

<script>
    <?php $this->beginBlock('js-end');?>
    $('body').attr('ontouchstart', '');
    new PhotoClip('#clipArea', {
        size: 260,
        outputSize: 640,
//        adaptive: ['60%', '80%'],
        file: '#file',
//        view: '#view',
        ok: '#clipBtn',
        loadStart: function () {
            console.log('开始读取照片');
        },
        loadComplete: function () {
            console.log('照片读取完成');
        },
        loadError: function (msg) {
            alert(msg);
        },
        done: function (dataURL) {
            if (!dataURL) {
                return
            }
            // 将图片URL地址赋值给name="image"
            $('#user-image').val(dataURL);
            $('#form').submit();
        },
        fail: function (msg) {
            alert(msg);
        }
    });
    // 点击+号 上传文件
    $('#add').click(function () {
        $('#file').click();
    });
    <?php $this->endBlock();?>
</script>

控制器部分

// 修改头像
public function actionEditImage()
{
    $model = User::findOne(Yii::$app->user->identity->id);
    if ($model->load(Yii::$app->request->post())) {
        $imageBase = Yii::$app->request->post("User");
        // 匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $imageBase['image'], $result)) {
            $type = $result[2];
            $folder = '/image/';
            $path = Yii::getAlias('@uploads') . $folder;
            if (FileHelper::createDirectory($path) === true) {
                $newFile = time() . '.' . $type;
                $base64_decode = base64_decode(str_replace($result[1], '', $imageBase['image']));
                // 保存头像
                if (file_put_contents($path . $newFile, $base64_decode)) {
                    // 删除旧的头像
                    if ($model->image) {
                        $old = Yii::getAlias('@uploads') . $model->image;
                        if (file_exists($old)) {
                            unlink($old);
                        }
                    }
                    $model->image= $folder . $newFile;
                    $model->save();
                    return $this->redirect(['/site']);
                } else {
                    Yii::$app->session->setFlash('error', '上传头像失败!');
                    return $this->redirect(['edit-portrait']);
                }
            }
        } else {
            Yii::$app->session->setFlash('error', '上传头像失败!');
            return $this->redirect(['edit-portrait']);
        }
    } else {
        return $this->render('edit-image', [
            'model' => $model
        ]);
    }
}

推荐阅读更多精彩内容