gpt4 book ai didi

javascript - Firebase Cloud Function 在 firestore create 上调整图像大小

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:54:12 26 4
gpt4 key购买 nike

我正在努力实现以下目标。但是,我不知道,因为我是 firebase 的初学者。

  1. 用户正在尝试上传带有图片的帖子
  2. 图片是从网络浏览器中选择的
  3. 当用户点击保存按钮时,我将所选图像上传到 firbase 存储并获取下载 URL。
  4. 将带有下载 url 的帖子数据插入到 firestore 数据库。

至此,我已经完成了。现在,我需要调整上传图片的大小。

为此,我正在尝试使用 Cloud Functions,每当将新条目添加到 firestore 数据库时,我都会调用 Cloud fountion,它可以访问图像的下载 URL,使用此下载 URL,我需要调整大小图像。请帮忙。

请让我知道,如果有任何更好的方法来实现这一点。 (我知道应该有 :P )

编辑 1

谢谢 Frank 的回复。

我有下面的云函数,每插入一个帖子都会被调用。我从 eventSnapshot 获取图像的下载 URL。我需要在该位置调整图像大小。请帮忙。

exports.resizeImage = functions.firestore
.document('posts/{postId}')
.onCreate(event => {
var eventSnapshot = event.data.data();
//In this eventSnapshot I am getting the document, and I can get the download URL from the document
});

我已经分析了创建缩略图的示例,但是为此,我需要
存储对象,只有当存储对象改变时才会调用。但是,当在 firestore 中调用 onWrite 时,我需要创建缩略图。

 exports.generateThumbnail = functions.storage.object().onChange((event) => {
// File and directory paths.
const filePath = event.data.name;
});

请告诉我如何通过检测 firestore 中的 onWrite 并使用 downLoadURL 来执行图像调整大小操作。

最佳答案

我也在 firestore 中创建了一个文档,我将其用作网站的后端。我也想调整图像大小(以适合卡片)并将 URL 写回 firestore。我找到了一个解决方案,它使用与通过将图像上传到存储而触发的标准示例不同的模式。

基本上,我将图像上传到存储,然后将 URL 写入我的应用程序页面中的 Firestore。然后,我使用 Firestore 的 onCreate() 触发器触发该函数。

该函数从 firestore 中获取“image_name”并使用它来获取存储中的文件引用。接下来,它遵循生成缩略图 firebase 示例的模式。

技巧是然后获取 signedUrl 并将其写回 img_src 中的 firestore。

如果其他人发现这有用:

const functions = require('firebase-functions');
const gcs = require('@google-cloud/storage')({keyFilename: 'service-key.json'});
const spawn = require('child-process-promise').spawn;
const path = require('path');
const os = require('os');
const fs = require('fs');

exports.createCard = functions.firestore
.document('work_cards/{cardID}')
.onCreate((snap, context) => {
const newCardData = snap.data()
const bucket = gcs.bucket('your-project-id.appspot.com')
const file = bucket.file(newCardData.image_name)
const tempFilePath = path.join(os.tmpdir(), file.name);
const thumbFileName = `thumb_${file.name}`;
const thumbFilePath = bucket.file(thumbFileName)
const contentType = file.contentType;
const metadata = {
contentType: contentType
};

return bucket.file(file.name).download({
destination: tempFilePath,
})
.then(() => {
return spawn('convert', [tempFilePath, '-thumbnail', '250x250', tempFilePath]);
})
.then(() => {
return bucket.upload(tempFilePath, {
destination: thumbFilePath,
metadata: metadata,
})
})
.then(() => {
return thumbFilePath.getSignedUrl({
action: 'read',
expires: '03-09-2491'
})
})
.then(signedUrls => {
const img_src = signedUrls[0]
return snap.ref.set({img_src}, {merge: true});
})
.then(() => {
bucket.file(file.name).delete()
fs.unlinkSync(tempFilePath)
return
})
});

关于javascript - Firebase Cloud Function 在 firestore create 上调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49575174/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com