您现在的位置是: 首页 >  技术分享 > 

图片压缩
传说中的小明 2024-09-01 15:42:06

如今的手机越来越智能,拍摄的图片越来越高清,也就意味着图片很多,如果不进行压缩处理,上传过程会漫长,同时在预览图片的时候资源加载也很慢,更消耗服务器的带宽资源。下面讲解一个图片压缩的方法,本案例使用的是三方插件js lrz.bundle.js,可自行下载到自己项目中。

本案例结合了layui,实现的是多图上传(单图上传,更简单,自行实现,不在啰嗦),具体代码如下:

1、html部分

<form class="layui-form layui-form-pane">
    <div class="layui-form-item">
        <label class="layui-form-label">上传图片:</label>
        <div class="layui-input-block">
            <button type="button" class="layui-btn" id="test2">
                多图上传
            </button>
        </div>
    </div>
    <div class="layui-form-item">
        <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
            预览图片
            <div class="layui-upload-list" id="demo2">

            </div>
        </blockquote>
        <div class="input_images">
            <!--input type="hidden" name="image[]" value="">-->
        </div>
    </div>
    <!-- 提交按钮  -->
    <div class="layui-form-item layui-btn_box">
        <button class="layui-btn layui-btn-fluid layui-btn-normal" id="submit">确认提交</button>
    </div>
</form>

2、script部分,注意替换自己的lrz.bundle.js路径

<script src="/static/lib/js/lrz.bundle.js"></script>
<script type="text/javascript">
    layui.use(['layer','form','upload'], function () {
        var layer = layui.layer;
        var $ = layui.jquery;
        var upload = layui.upload;
        var form = layui.form;
        var number = 5; // 最多上传个数
        form.render();

        //多图上传
        upload.render({
            elem: '#test2'
            ,url: '/admin/empty_fun'
            ,multiple: true
            ,accept: 'images' // 只允许上传图片
            ,number: number // 最多上传个数
            ,choose: function (obj) {
                // 统计文件的个数 是否超过最大值
                var length = $('#demo2 .img_box').length + 1;
                if (length > number) {
                    layer.msg('最多上传'+number+'张图片');
                    return false;
                }
                // 预览图片
                obj.preview(function(index, file, result){
                    var html = '<span class="img_box" id="'+index+'">' +
                        '<img src="' + result + '" alt="'+ file.name +'" class="layui-upload-img">' +
                        '<p class="up_tips up_suc">上传中</p>' +
                        '<img src="/uploads/image/close.png" alt="" class="close-img">' +
                        '</span>';
                    $('#demo2').append(html);

                    // 执行上传
                    lrz(file, {
                        quality: 0.8 //设置压缩率,可以自行调整 0-1之间
                    }).then(function (rst) {
                        $.ajax({
                            url: '/admin/base64_file',
                            type: 'post',
                            data: {type: 'image', event: 'image', base64_str: rst.base64},
                            success: function (ret) {
                                if (ret.code == 1) {
                                    $('#' + index).find('.up_tips').html('上传成功');
                                    $('.input_images').append('<input data-index="'+ index +'" type="hidden" name="image[]" value="' + ret.data.image + '">');
                                } else {
                                    $('#' + index).find('.up_tips').html('上传失败');
                                    $('.input_images').append('<input data-index="'+ index +'" type="hidden" name="image[]" value="">');
                                }
                            },
                            error: function (err) {
                                $('#' + index).find('.up_tips').html('上传失败');
                                $('.input_images').append('<input data-index="'+ index +'" type="hidden" name="image[]" value="">');
                                console.log(JSON.stringify((err)));
                            }
                        });
                    });
                });
            }
            ,error: function(err){
                //请求fail回调
            }
        });

        // 点击删除图片
        $('#demo2').on('click','.img_box .close-img',function () {
            var index = $(this).closest('.img_box').attr('id');
            // 删除dom元素
            $(this).closest('.img_box').remove();
            // 删除对应的input
            $('.input_images input').each(function (k,v) {
                var index1 = $(this).data('index');
                if (index1 == index) {
                    $(this).remove();
                }
            })
        });
    });
</script>

3、js中使用到两个接口,如下:

/**
 * 空方法(用于base64文件上传使用)
 */
public function empty_fun()
{
    $this->result('',1,'操作成功','json');
}

/**
 * @title base64上传文件
 *
 * @param $base64_str  string base64文件数据
 * @param $type string 类型:image=图片,video=视频,audio=音频
 * @param $event string 事件:avatar=头像,refund=售后,image=图片
 *
 */
public function base64_file()
{
    if(request()->isPost()){
        $type = $this->request->param('type','image');
        $event = $this->request->param('event','image');
        $base64_str = $this->request->param('base64_str','');
        if ($base64_str) {
            $base64_str = explode(',', $base64_str);
            $file = base64_decode($base64_str[1]);
            if (!$file) {
                $this->result('',0,'请上传图片','json');
            }
        } else {
            $this->result('',0,'请上传图片','json');
        }
        $savePath = './uploads/' . $type . '/' . $event . '/' . date("Ym") . "/". date("Ymd") . "/";
        if (!is_dir($savePath)) {
            mkdir($savePath, 0777, true);
        }
        $savePath = $savePath . uniqid() . '.png';
        $filePath = str_replace('./','/',$savePath);
        $res = file_put_contents($savePath, $file);
        if($res){
            $this->result(['image'=>$filePath, 'imageText'=>path_deal_with($filePath)],1,'上传成功','json');
        }else{
            $this->result('',0,'上传失败','json');
        }
    }else{
        $this->result('',0,'请求错误','json');
    }
}


Copyright © 2021
www.yunyakeji.cn All rights reserved. 小明博客 豫ICP备2020029140号-1