创建JavaScript中的图像缩略图广场(又不失宽高比) [英] Creating thumbnail squares of images in javascript (without losing aspect ratio)

查看:94
本文介绍了创建JavaScript中的图像缩略图广场(又不失宽高比)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提出一个客户端拖放文件上传脚本作为一个书签。上传之前我使用的文件API来读取图像转换为Base64格式并显示为缩略图。

I am making a client side Drag and Drop file upload script as a bookmarklet. Before uploading I am using the File API to read the images into base64 format and display them as thumbnails.

这是我的缩略图什么样子。我希望他们看起来更方,但没有失去他们的宽高比。 (请忽略的进度条)

This is how my thumbnails look like. I want them to look more square but without loosing their aspect ratio. (please ignore progress bar)

这是我想要的缩略图像,他们为中心,以分(高度,宽度)被裁掉。

This is how I want the thumbnails to be like, they are centered and being cropped based on min(height,width).

我可以做这个使用JavaScript只(通过脚本多变的款式会做)?请尽量确保您的解决方案将与图像的base64适合(图像是通过文件API作为数据读取URL后)。

Can I do this using javascript only (changing styles via script will do)? Please try to make sure that your solution will fit with base64 images (after the images are read via file API as DATA URL).

我已经上传这些精确的图像集合这里

I have uploaded these exact set of images here.

感谢您的帮助。

推荐答案

只是想分享我如何解决我的问题。
因为我想要一个纯粹的JavaScript的唯一的解决办法,我用一次性的画布元素做肮脏的工作。

Just wanted to share how I resolved my issue. Since I wanted a purely javascript only solution, I used throwaway canvas elements to do the dirty work.

下面是我的code为相同:

Here is my code for the same:

function resizeImage(url, width, height, callback, file) {
  console.log("In_resizeImage");
  var sourceImage = new Image();

  sourceImage.onload = (function (f) {
      return function (evt) {
        console.log("In_sourceImage_onload");
        console.log("sourceImage.width:" + sourceImage.width);
        console.log("sourceImage.height:" + sourceImage.height);
        var canvas = document.createElement("canvas");
        canvas.width = width;
        canvas.height = height;

        if (sourceImage.width == sourceImage.height) {
          canvas.getContext("2d").drawImage(sourceImage, 0, 0, width, height);
        } else {
          minVal = Math.min(sourceImage.width, sourceImage.height);
          if (sourceImage.width > sourceImage.height) {
            canvas.getContext("2d").drawImage(sourceImage, (sourceImage.width - minVal) / 2, 0, minVal, minVal, 0, 0, width, height);
          } else {
            canvas.getContext("2d").drawImage(sourceImage, 0, (sourceImage.height - minVal) / 2, minVal, minVal, 0, 0, width, height);
          }
        }
        callback(canvas.toDataURL(), f);
      }
    })(file);

  sourceImage.src = url;
}

我是直接与图像文件打交道,所以我能够使用Image对象。供他人使用,一点一点调整可能是必需的。

I was directly dealing with image files so I was able to use Image object. For others to use, little bit tweaking might be required.

这篇关于创建JavaScript中的图像缩略图广场(又不失宽高比)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆