如何将图像转换为缩略图

How to Convert image into Thumbnail

我有一张 cdn 图片 https://cdn.shopify.com/s/files/1/0234/8017/2591/products/young-man-in-bright-fashion_925x_f7029e2b-80f0-4a40-a87b-834b9a283c39.jpg,想将其转换成 Thumbnail

正在将图像转换为缩略图
如果我们有 CDNImage URL link 那么,我们需要将 link 转换为 blob 或 base64,然后将 base64 转换为 FILE type Object。这是将 CDN 转换为 base64 并将 base64 转换为 FILE 类型对象

的答案
Here is example of `FILE type Object`

: File
lastModified: 1591250106736
lastModifiedDate: Thu Jun 04 2020 11:25:06 GMT+0530 (India Standard 
Time) {}
name: "img.jpeg"
size: 369742
type: "image/jpeg"
webkitRelativePath: ""

现在,这是将 FILE 类型的对象转换为 thumbnail 的代码。它有两个参数,第一个参数是 file(它将被转换为 FILE 对象),另一个是 Bound-box [x,y] for thumbnail.

let boundBox = [100,100]
const toThumbnail = (file, boundBox) => {
if (!boundBox || boundBox.length != 2) {
throw "You need to give the boundBox"
}
var reader = new FileReader();
var canvas = document.createElement("canvas")
var ctx = canvas.getContext('2d');
return new Promise((resolve, reject) => {
reader.onload = function (event) {
  var img = new Image();
  img.onload = function () {
    var scaleRatio = Math.min(...boundBox) / Math.max(img.width, img.height)
    let w = img.width * scaleRatio
    let h = img.height * scaleRatio
    canvas.width = w;
    canvas.height = h;
    ctx.drawImage(img, 0, 0, w, h);
    let data = canvas.toDataURL(file.type)
    let myData = {
      url: data
    }
     // Here is thumbnail data >>>>>
    return resolve(myData) 
  }
  img.src = event.target.result;
}
reader.readAsDataURL(file);
})
}