【问题标题】:Display existing images as cropped thumbnail (and keep aspect ratio) in Dropzone.js instead of squished images?在 Dropzone.js 中将现有图像显示为裁剪的缩略图(并保持纵横比)而不是压扁的图像?
【发布时间】:2014-07-03 05:35:29
【问题描述】:

当我将图像上传到 Dropzone.js 时,它们会保持纵横比并被裁剪。 它们看起来像这样很好:

当我使用此代码显示以前上传的文件时:

...
         $.getJSON('files/list-all', function(data) {
            $.each(data, function(index, val) {
                var mockFile = { name: val.name, size: val.size };
                thisDropZone.options.addedfile.call(thisDropZone, mockFile);
                thisDropZone.options.thumbnail.call(thisDropZone, mockFile, "uploads/" + val.id + "." + val.extension);
            });
        });
...

我得到了这些压缩版本的图像:

所以问题是如何让缩略图在您上传时看起来像它们一样好?

【问题讨论】:

  • 我也很好奇添加绿色 (V) 图标和删除选项的正确方法是什么?非常感谢。
  • 同时在开发阶段我使用了 Croppa,一个 Laravel 包。

标签: dropzone.js


【解决方案1】:

同样的问题,我的解决方法。这不是裁剪效果,而是保持纵横比。它还将图片在框架内居中。

它通过在 dropzone 创建时的 'init' 选项中实现 'fileadded' 侦听器来实现。然后,调整图像。

步骤:

  1. 在预览框中查找 IMG 元素;
  2. 等待图片加载(之前的尺寸不可用);
  3. 检索其尺寸;
  4. 计算纵横比、假想尺寸和位置;
  5. 定义内联 css(覆盖 css 类“dropzone”)。

上市:

var thisDropZone = new Dropzone($("#thisDropZone"), {
    url: "files/upload",
    init: function () {
        this.on("addedfile", function (file) {
            var img = $(file.previewTemplate).find("img");
            img[0].onload = function () {
                var max = this.width > this.height ? this.width : this.height;
                var ratio = 100.0 / max;

                var width = this.width * ratio;
                var height = this.height * ratio;

                img.css({
                    width: width + "px",
                    height: height + "px",
                    top: ((100 - height) / 2) + "px",
                    left: ((100 - width) / 2) + "px"
                });
            };
        }
    }
});

循环幻数“100”是 IMG 元素的“width”和“weight”属性值,由其默认样式表“dropzone.css”中的 css 类“.dropzone”定义。

要实现这一点,你不能像你那样调用'addfile'事件;你必须像这样触发它:

$.getJSON('files/list-all', function(data) {
    $.each(data, function(index, val) {
        var mockFile = { name: val.name, size: val.size };

        thisDropZone.emit("addedfile", mockFile);
        thisDropZone.emit("thumbnail", mockFile, "uploads/" + val.id + "." + val.extension);
    });
});

希望对你有帮助!

【讨论】:

  • 生成缩略图并与原始图像一起存储不是更好吗?否则,您将下载完整尺寸的图像。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-31
  • 2012-05-23
  • 1970-01-01
  • 2017-04-11
  • 1970-01-01
相关资源
最近更新 更多