Firebase

How to use Firebase Cloud Functions to resize images on upload?

Uncover the secrets of using Firebase Cloud Functions to resize images during uploads. Boost your web or mobile app's efficiency with this straightforward guide.

Developer profile skeleton
a developer thinking

Overview

Utilizing Firebase Cloud Functions to resize images when they're uploaded can be a game-changer for managing image sizes in an application. This method cuts down on bandwidth usage and boosts overall performance. The article will first explain what Firebase Cloud Functions are, along with their various uses and benefits. Following that, there's a detailed look at how to practically apply these functions to resize images upon upload. The technical details are broken down simply, so implementation becomes straightforward. It will also highlight some tips and common issues to watch out for, ensuring a smoother experience. By the end, expect a strong grasp of using Firebase Cloud Functions for image resizing.

Get a Free No-Code Consultation
Meet with Will, CEO at Bootstrapped to get a Free No-Code Consultation
Book a Call
Will Hawkins
CEO at Bootstrapped

How to use Firebase Cloud Functions to resize images on upload?

Step 1: Set up Firebase Cloud Functions

Alright, first things first. Make sure you've got Node.js and npm all set up on your system. Then, head over to your project directory and fire up Firebase with this command:

firebase init

When the CLI asks, "Which Firebase CLI features do you want to set up for this folder?", go ahead and pick 'Functions'. Next, choose the Firebase project you created earlier in the Firebase console for 'Select a default Firebase project for this directory'.

Step 2: Install the Google Cloud Storage and Firebase-admin modules

Now, let's get those necessary modules installed. Navigate to the functions directory in your project and run these commands:

npm install --save @google-cloud/storage
npm install --save firebase-admin

Step 3: Install The Sharp Module

Sharp is a fantastic module for handling images in Node.js. You can install it with this command:

npm install --save sharp

Step 4: Write a Function to Trigger on File Upload

Next up, create an index.js file in the functions directory and import the necessary modules:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const gcs = require('@google-cloud/storage')();
const sharp = require('sharp');

Now, let's write a Cloud Function that triggers every time a new file is uploaded to a specific storage bucket:

exports.onFileUpload = functions.storage.bucket('my_custom_bucket').object().onFinalize((object) => {
...
});

The 'object' parameter here is a reference to the file that was just uploaded.

Step 5: Resize the Image and Upload

Time to resize that image! Inside the onFinalize function, add this code:

const filePath = object.name;
const bucket = gcs.bucket(object.bucket);
const fileName = filePath.split('/').pop();
const tempFilePath = `/tmp/${fileName}`;
const metadata = object.metadata;

return bucket.file(filePath).download({
    destination: tempFilePath,
})
.then(() => {
    return sharp(tempFilePath)
        .resize(800, 800)
        .toFile(`${tempFilePath}_resized`);
})
.then(() => {
    return bucket.upload(`${tempFilePath}_resized`, {
        destination: `resized_images/${fileName}`,
        metadata: metadata,
    });
});

This code downloads the newly uploaded file to a temporary location, resizes it, and then re-uploads it to the 'resized_images' directory in the same storage bucket. Pretty neat, right?

Step 6: Deploy the Cloud Function

Finally, let's get this Cloud Function live. Deploy it with this command:

firebase deploy --only functions

Once this command finishes, your Firebase Cloud Function is up and running. Now, whenever a new file is uploaded to the storage bucket 'my_custom_bucket', it will automatically get resized to 800x800 pixels and re-uploaded into the 'resized_images' directory.

Explore more Firebase tutorials

Complete Guide to Firebase: Tutorials, Tips, and Best Practices

Explore our Firebase tutorials directory - an essential resource for learning how to create, deploy and manage robust server-side applications with ease and efficiency.

Why are companies choosing Bootstrapped?

40-60%

Faster with no-code

Nocode tools allow us to develop and deploy your new application 40-60% faster than regular app development methods.

90 days

From idea to MVP

Save time, money, and energy with an optimized hiring process. Access a pool of experts who are sourced, vetted, and matched to meet your precise requirements.

1 283 apps

built by our developers

With the Bootstrapped platform, managing projects and developers has never been easier.

hero graphic

Our capabilities

Bootstrapped offers a comprehensive suite of capabilities tailored for startups. Our expertise spans web and mobile app development, utilizing the latest technologies to ensure high performance and scalability. The team excels in creating intuitive user interfaces and seamless user experiences. We employ agile methodologies for flexible and efficient project management, ensuring timely delivery and adaptability to changing requirements. Additionally, Bootstrapped provides continuous support and maintenance, helping startups grow and evolve their digital products. Our services are designed to be affordable and high-quality, making them an ideal partner for new ventures.

Engineered for you

1

Fast Development: Bootstrapped specializes in helping startup founders build web and mobile apps quickly, ensuring a fast go-to-market strategy.

2

Tailored Solutions: The company offers customized app development, adapting to specific business needs and goals, which ensures your app stands out in the competitive market.

3

Expert Team: With a team of experienced developers and designers, Bootstrapped ensures high-quality, reliable, and scalable app solutions.

4

Affordable Pricing: Ideal for startups, Bootstrapped offers cost-effective development services without compromising on quality.

5

Supportive Partnership: Beyond development, Bootstrapped provides ongoing support and consultation, fostering long-term success for your startup.

6

Agile Methodology: Utilizing agile development practices, Bootstrapped ensures flexibility, iterative progress, and swift adaptation to changes, enhancing project success.

Yes, if you can dream it, we can build it.