Node.js 如何将图像转换为缩略图
我有一张Node.js 如何将图像转换为缩略图,node.js,image,thumbnails,Node.js,Image,Thumbnails,我有一张cdnImagehttps://cdn.shopify.com/s/files/1/0234/8017/2591/products/young-man-in-bright-fashion_925x_f7029e2b-80f0-4a40-a87b-834b9a283c39.jpg,并希望将其转换为缩略图将图像转换为缩略图 如果我们有CDN或图像URL链接,那么我们需要将该链接转换为blob或base64,然后将base64转换为文件类型对象。下面是将CDN转换为base64并将base64
cdn
Imagehttps://cdn.shopify.com/s/files/1/0234/8017/2591/products/young-man-in-bright-fashion_925x_f7029e2b-80f0-4a40-a87b-834b9a283c39.jpg
,并希望将其转换为缩略图
将图像转换为缩略图如果我们有
CDN
或图像URL
链接,那么我们需要将该链接转换为blob或base64,然后将base64转换为文件类型对象
。下面是将CDN
转换为base64并将base64转换为文件类型对象的答案
现在,下面是将文件
类型对象转换为缩略图
的代码。它有两个参数,第一个参数是file
(它将被转换为文件对象),另一个参数是用于缩略图的绑定框[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);
})
}
这和React有什么关系?你说的Thumnail到底是什么意思?看起来更小?小一点?另一种格式?我一直在使用react应用程序,我必须向用户显示缩略图,而不是原始图像。我删除了react JS标记,因为您没有提出特定于react的问题,也没有共享任何react代码,等等。。如果React是相关的,那么请在上下文中包含React代码。甚至你的答案也完全不相关。仅仅因为您正在使用React并不意味着它与图像转换/大小调整问题相关。请仅添加与问题相关的标记。例如,如果你在windows机器上工作,这并不意味着你应该用windows标记问题。
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);
})
}