2
votes

I'd like to do the following: Create a Google Cloud Function (http triggered) that simply read an image file from a bucket (Google Cloud Storage) and send it as a response.

I've tried some combinations and I think that it should be something like that:

'use strict';
const gcs = require('@google-cloud/storage')();

exports.sendImage = function sendImage(req, res) {
    let bucket = gcs.bucket('my-bucket-name');
    let myImage = bucket.file('my-image-file.jpg');


    res.contentType('image/jpeg');
    res.end(myImage, 'binary');
};

The function above deploys successfully but when I trigger it just using the url (on browser) it shows no results.

I'm doing that as simple as possible because if it works with one image, I can improve the code to call any image.

My final goal is to have something similar to that showed on this post: https://medium.com/google-cloud/uploading-resizing-and-serving-images-with-google-cloud-platform-ca9631a2c556

But running on Google Cloud Functions. If I manage to send a simple image, I can use some module such as node-image-resize to the final result.

1

1 Answers

12
votes

Well I could find it by myself and I think it can help a lot other people. So do the following:

1 - Create a bucket on Google Cloud Storage, let's say the name is [my-bucket]

2 - Create a Google Cloud Function, let's name it imageServer.

3 - Don't forget to edit the package.json file. My one was as follows:

{
  "name": "image-server",
  "version": "0.0.1",
    "dependencies": {
    "@google-cloud/storage": "^1.2.1"
  }
}

4 - The code to send a simple image is really simple (after I figured that out):

'use strict';

const gcs = require('@google-cloud/storage')();

exports.imageServer = function imageSender(req, res) {
  let file = gcs.bucket('my-bucket').file('test-1.jpg');
  let readStream = file.createReadStream();

  res.setHeader("content-type", "image/jpeg");
  readStream.pipe(res);

};

Obs: The testing image is the file named [test-1.jpg] and it's on bucket's root. So, from here, I was able to send it to the browser. Now it's just a matter of changing the code to achieve my primary goal as I told on my question.

I hope it helps.

Reference links: Google Cloud Storage NPM Google cloud Functions Hello World tutorial