【问题标题】:How to Convert image into Thumbnail如何将图像转换为缩略图
【发布时间】:2021-07-23 14:15:13
【问题描述】:

我有一个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

【问题讨论】:

  • 这和 React 有什么关系?
  • thumnbnail 到底是什么意思?看起来更小?尺寸更小?另一种格式?
  • 我一直在开发 react 应用程序,我必须向用户显示缩略图而不是原始图像。
  • 我删除了 reactjs 标签,因为你没有提出特定于 React 的问题,没有分享任何 React 代码等。如果 React 是相关的,那么请包含你的 React 代码作为上下文。甚至您的答案也完全与 React 无关。仅仅因为您正在使用 React 并不意味着它与图像转换/调整大小的问题有关。
  • 请只添加与问题相关的标签。例如。如果你在 Windows 机器上工作,这并不意味着你应该用 windows 标记问题。

标签: node.js image thumbnails


【解决方案1】:

将图像转换为缩略图
如果我们有CDNImage URL 链接,我们需要将该链接转换为blob 或base64,然后将base64 转换为FILE type Object。这是将CDN 转换为base64 并将base64 转换为FILE 类型对象的答案 https://stackoverflow.com/a/62227874/13081559

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 类型 Object 转换为 thumbnail 的代码。它有两个参数,第一个参数是file(它将被转换为FILE对象),另一个是Bound-box [x,y]缩略图。

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);
})
}

【讨论】:

    猜你喜欢
    • 2011-06-05
    • 1970-01-01
    • 2015-11-17
    • 2018-09-14
    • 1970-01-01
    • 2012-04-04
    • 2015-05-30
    • 1970-01-01
    相关资源
    最近更新 更多