调整存储在Firebase存储中的所有现有图像,并通过API调用更新新调整大小的图像URL到数据库

发布于 2025-01-31 06:19:28 字数 994 浏览 3 评论 0原文

我需要调整存储在Firebase商店中的新图像大小。对于新图像,我启用了Firebase的调整大小扩展。对于现有图像,如何调整图像大小并获取新调整大小的图像URL以通过API更新回数据库。

这是我的Firebase功能,可以从数据库中获取现有的图像URL。我的问题是如何调整图像大小并获取新图像URL?

const函数= require(“ firebase-intuntions”); const axios = require(“ axios”);

异步函数getAlbums(){

const endpoint = "https://api.mydomain.com/graphql";
const headers = {
  "content-type": "application/json",
};

const graphqlQuery = {
  "query": `query Albums {
    albums {
      id
      album_cover
    }
  }`
};
functions.logger.info("Call API");
const response = await axios({
  url: endpoint,
  method: 'post',
  headers: headers,
  data: graphqlQuery
});

if(response.errors) {
    functions.logger.info("API ERROR : ", response.errors) // errors if any
} else {
    return response.data.data.albums;
}
}

exports.manualGenerateResizedImage = functions.https.onRequest(async () => {
    const albums = await getAlbums();
    functions.logger.info("No. of Album : ", albums.length);
});

I have requirement to resize new and existing images stored in firebase store. For new image, I enabled firebase's resize image extension. For existing image, how can I resized the image and get the newly resized image url to update back to database via api.

Here is my firebase function to get existing image urls from database. My question is how to resize the image and get the new image url?

const functions = require("firebase-functions");
const axios =require("axios");

async function getAlbums() {

const endpoint = "https://api.mydomain.com/graphql";
const headers = {
  "content-type": "application/json",
};

const graphqlQuery = {
  "query": `query Albums {
    albums {
      id
      album_cover
    }
  }`
};
functions.logger.info("Call API");
const response = await axios({
  url: endpoint,
  method: 'post',
  headers: headers,
  data: graphqlQuery
});

if(response.errors) {
    functions.logger.info("API ERROR : ", response.errors) // errors if any
} else {
    return response.data.data.albums;
}
}

exports.manualGenerateResizedImage = functions.https.onRequest(async () => {
    const albums = await getAlbums();
    functions.logger.info("No. of Album : ", albums.length);
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

花间憩 2025-02-07 06:19:28

我认为下面答案来自雷诺·塔内克(Renaud Tarnec)肯定会为您提供帮助。

如果您查看“调整图像”扩展程序的A>,您会看到构成构成扩展的云函数是由a onfinalize 事件,这意味着:

当新对象(或现有对象的新一代)是
成功创建的存储桶。这包括复制或重写
现有对象。

因此,如果不重写/再生现有图像,则不会触发扩展名。

但是,您可以轻松地编写自己的云功能,该功能可以执行相同的操作,但可以通过调用特定URL触发( https云功能)或通过在临时firestore集合中创建新文档(背景触发cf )。

该云功能将执行以下步骤:

  1. 获取存储桶的所有文件,请参阅 getfiles> ()
    Google Cloud Storage Node.js客户端API。此方法返回
    getfilesresponse object object 是文件实例的阵列。
  2. 通过在数组上循环,对于每个文件,请检查文件是否具有
    在存储桶中相应的调整大小图像(取决于您的方式
    配置了扩展名,调整大小的图像可能是特定的
    文件夹)
  3. 如果文件没有相应的调整大小映像,请执行
    该文件的扩展云功能的相同业务逻辑。

有一个官方的云功能 sample 显示如何创建如何创建云存储触发的firebase函数将创建从上传的映像创建调整大小的缩略图并将其上传到数据库URL(请参阅index.js file的最后一行)

注意:如果您有很多可以处理的文件,则可能很可能有效通过批处理,由于云功能执行的限制为9分钟。另外,根据要处理的图像数量,您可能需要增加超时值和/或云功能分配的内存,请参见 https://firebase.google.com/docs/functions/manage-functions/manage-functions#sety_time_time_time_and_and_memory_allocation

I think the below answer from Renaud Tarnec will definitely help you.

If you look at the code of the "Resize Images" extension, you will see that the Cloud Function that underlies the extension is triggered by a onFinalize event, which means:

When a new object (or a new generation of an existing object) is
successfully created in the bucket. This includes copying or rewriting
an existing object.

So, without rewriting/regenerating the existing images the Extension will not be triggered.

However, you could easily write your own Cloud Function that does the same thing but is triggered, for example, by a call to a specific URL (HTTPS cloud Function) or by creating a new document in a temporary Firestore Collection (background triggered CF).

This Cloud Function would execute the following steps:

  1. Get all the files of your bucket, see the getFiles() method of the
    Google Cloud Storage Node.js Client API. This method returns a
    GetFilesResponse object which is an Array of File instances.
  2. By looping over the array, for each file, check if the file has a
    corresponding resized image in the bucket (depending on the way you
    configured the Extension, the resized images may be in a specific
    folder)
  3. If a file does not have a corresponding resized image, execute the
    same business logic of the Extension Cloud Function for this File.

There is an official Cloud Function sample which shows how to create a Cloud Storage triggered Firebase Function that will create resized thumbnails from uploaded images and upload them to the database URL, (see the last lines of index.js file)

Note : If you have a lot of files to treat, you should most probably work by batch, since there is a limit of 9 minutes for Cloud Function execution. Also, depending on the number of images to treat, you may need to increase the timeout value and/or the allocated memory of your Cloud Function, see https://firebase.google.com/docs/functions/manage-functions#set_timeout_and_memory_allocation

飘然心甜 2025-02-07 06:19:28

如果有人需要它。这就是我调整现有图像大小的方式。

const functions = require("firebase-functions");
const axios = require("axios");
const { Storage } = require("@google-cloud/storage");

const storage = new Storage();

// Don't forget to replace with your bucket name
const bucket = storage.bucket("projectid.appspot.com");

async function getAlbums() {
  const endpoint = "https://api.mydomain.com/graphql";
  const headers = {
    "content-type": "application/json",
  };

  const graphqlQuery = {
    query: `query Albums {
        albums {
          id
          album_cover
        }
      }`,
  };
  const response = await axios({
     url: endpoint,
     method: "post",
     headers: headers,
     data: graphqlQuery,
   });

  if (response.errors) {
    functions.logger.error("API ERROR : ", response.errors); // errors 
if any
  } else {
    return response.data.data.albums;
  }
}

function getFileName(url) {
  var decodeURI = decodeURIComponent(url);
  var index = decodeURI.lastIndexOf("/") + 1;
  var filenameWithParam = decodeURI.substr(index);
  index = filenameWithParam.lastIndexOf("?");
  var filename = filenameWithParam.substr(0, index);
  return filename;
}

function getFileNameFromFirestore(url) {
  var index = url.lastIndexOf("/") + 1;
  var filename = url.substr(index);
  return filename;
}

const triggerBucketEvent = async () => {
  bucket.getFiles(
    {
      prefix: "images/albums", // you can add a path prefix
      autoPaginate: false,
    },
    async (err, files) => {
      if (err) {
        functions.logger.error(err);
        return;
      }

      const albums = await getAlbums();

       await Promise.all(
        files.map((file) => {
          var fileName = getFileNameFromFirestore(file.name);

          var result = albums.find((obj) => {
             return getFileName(obj.album_cover) === fileName;
          });

      if (result) {
        var file_ext = fileName.substr(
          (Math.max(0, fileName.lastIndexOf(".")) || Infinity) + 1
        );
        var newFileName = result.id + "." + file_ext;
        // Copy each file on thumbs directory with the different name
        file.copy("images/albums/" + newFileName);

      } else {
        functions.logger.info(file.name, " not found in album list!");
      }
    })
  );
}
  );
};

exports.manualGenerateResizedImage = functions.https.onRequest(async () => {
  await triggerBucketEvent();
});

In case someone need it. This is how I resized existing image.

const functions = require("firebase-functions");
const axios = require("axios");
const { Storage } = require("@google-cloud/storage");

const storage = new Storage();

// Don't forget to replace with your bucket name
const bucket = storage.bucket("projectid.appspot.com");

async function getAlbums() {
  const endpoint = "https://api.mydomain.com/graphql";
  const headers = {
    "content-type": "application/json",
  };

  const graphqlQuery = {
    query: `query Albums {
        albums {
          id
          album_cover
        }
      }`,
  };
  const response = await axios({
     url: endpoint,
     method: "post",
     headers: headers,
     data: graphqlQuery,
   });

  if (response.errors) {
    functions.logger.error("API ERROR : ", response.errors); // errors 
if any
  } else {
    return response.data.data.albums;
  }
}

function getFileName(url) {
  var decodeURI = decodeURIComponent(url);
  var index = decodeURI.lastIndexOf("/") + 1;
  var filenameWithParam = decodeURI.substr(index);
  index = filenameWithParam.lastIndexOf("?");
  var filename = filenameWithParam.substr(0, index);
  return filename;
}

function getFileNameFromFirestore(url) {
  var index = url.lastIndexOf("/") + 1;
  var filename = url.substr(index);
  return filename;
}

const triggerBucketEvent = async () => {
  bucket.getFiles(
    {
      prefix: "images/albums", // you can add a path prefix
      autoPaginate: false,
    },
    async (err, files) => {
      if (err) {
        functions.logger.error(err);
        return;
      }

      const albums = await getAlbums();

       await Promise.all(
        files.map((file) => {
          var fileName = getFileNameFromFirestore(file.name);

          var result = albums.find((obj) => {
             return getFileName(obj.album_cover) === fileName;
          });

      if (result) {
        var file_ext = fileName.substr(
          (Math.max(0, fileName.lastIndexOf(".")) || Infinity) + 1
        );
        var newFileName = result.id + "." + file_ext;
        // Copy each file on thumbs directory with the different name
        file.copy("images/albums/" + newFileName);

      } else {
        functions.logger.info(file.name, " not found in album list!");
      }
    })
  );
}
  );
};

exports.manualGenerateResizedImage = functions.https.onRequest(async () => {
  await triggerBucketEvent();
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文