All Products
Document Center

Image processing

Last Updated: Mar 22, 2019

This section describes how to use the jimp image processing database of Node.js to scale images. In this example, you can learn about:

  • How to upload a third-party dependent database
  • How to enable the logging function and view the function running logs

In this example, it is assumed that the function code is stored in the code directory, the source and result images are stored in the data directory, and the “demo” service exists in Function Compute. If you are not familiar with service creation and other background information, see hello world application example.

Run fcli shell to enter the interactive mode.

Install a third-party dependent database

Node.js version

As functions depend on the third-party image processing database jimp, it must be installed in the code directory and zipped and uploaded with the function source code. fcli provides you with a local sandbox environment, which is consistent with the function running environment in Function Compute. In the sandbox environment, you can conveniently install the third-party database and perform local debugging.

  1. Run sbox -d code -t nodejs6. -d specifies the directory of the code, which is attached to the “/code” location in the sandbox environment. -t specifies the language type.

  2. In the sandbox environment, run npm init -f to generate package.json required by Node.js 6, and then run npm install jimp to install the dependent database.

  3. After the installation is completed, run exit to exit the sandbox environment. At this time, the jimp has been installed in the code directory.


    1. To run the sbox command, you must first have docker installed on your host. For more information about how to install docker, see the relevant documentation.

    2. The image used by sbox is available on the official docker image database.

    3. You must have the root permission when using docker in Linux. Therefore, you must use sudo fcli shell to start the command line tool, or you can refer to the relevant documentation to change the settings and then manage docker as a non-root user.

    4. We recommend that you pack third-party databases, test functions, and investigate issues in the sandbox environment. This can reducde unexpected errors that are caused by inconsistency between the development and running environments. In particular, when your functions depend on binary files, it will help a lot if you compile the relevant dependencies in the sandbox environment.

      1. >>> sbox -d code -t nodejs6
      2. Entering the container. Your code is in the /code direcotry.
      3. root@df9fc6428140:/code# npm init -f
      4. npm info it worked if it ends with ok
      5. npm info using npm@3.10.10
      6. npm info using node@v6.10.3
      7. npm WARN using --force I sure hope you know what you are doing.
      8. Wrote to /code/package.json:
      9. {
      10. "name": "code",
      11. "version": "1.0.0",
      12. "description": "",
      13. "main": "index.js",
      14. "dependencies": {
      15. "jimp": "^0.2.28"
      16. },
      17. "devDependencies": {},
      18. "scripts": {
      19. "test": "echo \"Error: no test specified\" && exit 1"
      20. },
      21. "keywords": [],
      22. "author": "",
      23. "license": "ISC"
      24. }
      25. npm info init written successfully
      26. npm info ok
      27. root@df9fc6428140:/code# npm install jimp
      28. npm info it worked if it ends with ok
      29. ...
      30. npm info lifecycle jimp@0.2.28~postinstall: jimp@0.2.28
      31. code@1.0.0 /code
      32. -- jimp@0.2.28
      33. npm WARN code@1.0.0 No description
      34. npm WARN code@1.0.0 No repository field.
      35. npm info ok
      36. root@df9fc6428140:/code# exit
      37. exit

Python version:

In the Python version, the wand image processing database is used in this example. Currently, the Python running environment of Function Compute has already included the wand module. Therefore, the third-party database does not need to be installed in the sandbox environment. For more information about the common modules included in the Python running environment of Function Compute, see Python programming guide.

Note: Click the last row of this page to view the complete demo shell operation video should you get stuck at any step.

Write codes

In the code directory, create the image_process.js file to implement the resize function. The source image is imported as the event parameter.

  1. 'use strict';
  2. var jimp = require("jimp");
  3. var fs = require("fs")
  4. module.exports.resize = function(event, context, callback) {
  5. // The imported event is a PNG image. Write it to the /tmp directory.
  6. fs.writeFileSync("/tmp/serverless.png", event)
  7. // Read the PNG image in the /tmp directory, call the jimp database to complete resize, and write the result image to the /tmp directory.
  8."/tmp/serverless.png", function(err, image) {
  9. if (err) {
  10. console.error("failed to read image");
  11. callback(err)
  12. return
  13. }
  14. image.resize(128, 128)
  15. .write("/tmp/serverless_128.png", function(err) {
  16. if (err) {
  17. console.error("failed to write image");
  18. callback(err)
  19. return
  20. }
  21. // Read the result image from the /tmp directory and return the result as the response.
  22. callback(null, fs.readFileSync("/tmp/serverless_128.png"))
  23. })
  24. });
  25. };
  1. # -*- coding: utf-8 -*-
  2. from wand.image import Image
  3. def resize(event, context):
  4. with Image(blob=event) as img:
  5. with img.clone() as i:
  6. i.resize(128, 128)
  7. return i.make_blob()

Create Log Service logstore

Function Compute stores the function running logs in your specified logstore. Run mkl -p fc -s demo to create the log project fc and logstore demo on Log Service.


  1. If you have not activated Log Service yet, activate it first. If you have already activated it, check whether you have outstanding balance.

  2. Skip this step if you already have logstore.

  3. If you copy and run the preceding command, the following error may be reported. This is because Log Service requires a globally unique project name. In this case, you must change the project name. For more information, see Log Service documentation.

    1. Error: {
    2. "errorCode": "ProjectAlreadyExist",
    3. "errorMessage": "Project fc already exist",
    4. ...
    5. }
  4. You must pay for using the log resources separtely. Especially note that Log Service charges certain resource reservation fees, which means that even if you do not write any logs, you are charged at least RMB 0.04/day. For more charging details, see the relevant documentation.

  5. As logs are important information for debugging and fault diagnosis, we recommend that you activate Log Service to store Function Compute logs.

    1. songluo@demo $ ./fcli shell
    2. Welcome to the function compute world. Have fun!
    3. >>> mkl --help
    4. mkl: create the log project/store
    5. flags:
    6. --help
    7. -p, --project string the log project
    8. --shard int the shard count of the log store (default 1)
    9. -s, --store string the log store
    10. --ttl int the ttl of the log store, in days (default 30)
    11. >>> mkl -p fc -s demo
    12. Note: you have to pay at least 0.04 RMB/day for the log store resource. For the detail billing info please refer to:
    14. Do you want to create the log store? [y/n]
    15. y
    16. >>>

Grant a write permission to the Function Compute logstore

Logs are your private resources. Therefore, Function Compute must have your explicit authorization before accessing logs. Run grant demo and authorize Function Compute to write the function running log under demo to the specified logstore as prompted. Role authorization of Function Compute is based on Alibaba Cloud RAM. For more information, see the relevant documentation.

Note: If you are using a RAM subaccount, the following error may be reported when you run the grant command. This is because your account does not have the create policy permission. You must be authorized by the primary account to perform relevant operations.

  1. Error: failed to create policy write-fc-logs due to {
  2. "HttpStatus": 404,
  3. "HostId": "",
  4. "Code": "Inactive",
  5. "Message": "Account is inactive to this service"
  6. }
  1. songluo@demo $ ./fcli shell
  2. Welcome to the function compute world. Have fun!
  3. >>> grant demo
  4. Please input the role name:
  5. fc-logs
  6. Please input the policy name:
  7. write-demo-logs
  8. Permission grant scenarios:
  9. 1. Allow FC write function logs to your log store.
  10. 2. Allow FC copy code from your OSS location.
  11. Please input your choice [1-2]:
  12. 1
  13. Please input the log project: fc
  14. Please input the log store: demo
  15. ...grant success
  16. >>> info /ram/roles/fc-logs
  17. Role:
  18. {
  19. "RoleId": "338942517712635876",
  20. "RoleName": "fc-logs",
  21. "Arn": "acs:ram::12345678:role/fc-logs",
  22. "Description": "create the role fc-logs",
  23. "AssumeRolePolicyDocument": "{\n \"Statement\": [{\n \"Action\": \"sts:AssumeRole\",\n \"Effect\": \"Allow\",\n \"Principal\": {\"Service\": [\"\"]}}],\n \"Version\": \"1\"}",
  24. "CreateDate": "2017-09-19T09:12:12Z"
  25. }
  26. Attached policies:
  27. [{write-demo-logs Custom create the policy write-demo-logs v5 0} {fc-copy-code-all Custom create the policy fc-copy-code-all v1 0} {fc-oss-rw Custom create the policy fc-oss-rw v1 0}]

Create and call a function

Run mkf demo/resize -t nodejs6 -h image_process.resize -d code to create the resize function in Function Compute, which belongs to the demo service.

Note: In the Python version, runtime is set to python2.7.

  1. songluo@demo $ ./fcli shell
  2. Welcome to the function compute world. Have fun!
  3. >>> mkf demo/resize -t nodejs6 -h image_process.resize -d code

Call a function and view logs

If the source image serverless.png is in the data directory, run invk demo/resize -f data/serverless.png -o data/serverless_128.png to resize the image.

Run logs demo to view the logs of the entire demo service, and run logs demo/resize to view the logs of the specified function.

  1. songluo@demo $ ls
  2. code data fcli
  3. songluo@demo $ cd code
  4. songluo@code $ ls
  5. hello_world.js image_process.js node_modules
  6. songluo@demo $ fcli shell
  7. Welcome to the function compute world. Have fun!
  8. >>> ls demo
  9. resize
  10. world
  11. >>> invk demo/resize -f data/serverless.png -o data/serverless_128.png
  12. >>> logs demo/resize
  13. 2017-09-28T15:54:35+08:00 serviceName:demo functionName:resize message:2017-09-28T07:54:35.426Z [info] FunctionCompute nodejs runtime inited.
  14. 2017-09-28T15:54:35+08:00 serviceName:demo functionName:resize message:FC Invoke Start RequestId: c3c4b57d-847b-42c3-daf0-4f3a8cc278e4
  15. 2017-09-28T15:54:35+08:00 serviceName:demo functionName:resize message:FC Invoke End RequestId: c3c4b57d-847b-42c3-daf0-4f3a8cc278e4

To view the complete demo operation video of example 3, see image_process.