全部产品
云市场

2. 创建函数

更新时间:2018-09-01 13:08:45

根据您的使用习惯,您可以使用 可视化工具函数计算控制台命令行工具 fcli 创建函数。

注意:您的函数需要和 OSS Bucket 在同一区域,OSS Bucket 的地域为华东2,函数所在服务的地域也选择华东2。

  1. 新建服务,本示例服务名称为 demo,地域为华东2,日志项目为 test-project,日志仓库为 test-logstore,角色创建方式为新建角色,系统授权模板选择 AliyunOSSFullAccessAliyunLogFullAccess

  2. 新建函数,选择空白函数模板,不创建触发器,本示例函数名称为 resize,运行环境选择 python,其他参数使用默认值。

  3. 函数代码如下:

    1. 'use strict';
    2. console.log('Loading function ...');
    3. var oss = require('ali-oss').Wrapper;
    4. var fs = require('fs');
    5. var jimp = require("jimp");
    6. module.exports.resize = function (eventBuf, ctx, callback) {
    7. console.log('Received event:', eventBuf.toString());
    8. var event = JSON.parse(eventBuf);
    9. var ossEvent = event.events[0];
    10. // Required by OSS sdk: OSS region is prefixed with "oss-", e.g. "oss-cn-shanghai"
    11. var ossRegion = "oss-" + ossEvent.region;
    12. // Create oss client.
    13. var client = new oss({
    14. region: ossRegion,
    15. // Credentials can be retrieved from context
    16. accessKeyId: ctx.credentials.accessKeyId,
    17. accessKeySecret: ctx.credentials.accessKeySecret,
    18. stsToken: ctx.credentials.securityToken
    19. });
    20. // Bucket name is from OSS event
    21. client.useBucket(ossEvent.oss.bucket.name);
    22. // Processed images will be saved to processed/
    23. var newKey = ossEvent.oss.object.key.replace("source/", "processed/");
    24. var tmpFile = "/tmp/processed.png";
    25. // Get object
    26. console.log('Getting object: ', ossEvent.oss.object.key)
    27. client.get(ossEvent.oss.object.key).then(function (val) {
    28. // Read object from buffer
    29. jimp.read(val.content, function (err, image) {
    30. if (err) {
    31. console.error("Failed to read image");
    32. callback(err);
    33. return;
    34. }
    35. // Resize the image and save it to a tmp file
    36. image.resize(128, 128).write(tmpFile, function (err) {
    37. if (err) {
    38. console.error("Failed to write image locally");
    39. callback(err);
    40. return;
    41. }
    42. // Putting object back to OSS with the new key
    43. console.log('Putting object: ', newKey);
    44. client.put(newKey, tmpFile).then(function (val) {
    45. console.log('Put object:', val);
    46. callback(null, val);
    47. return;
    48. }).catch(function (err) {
    49. console.error('Failed to put object: %j', err);
    50. callback(err);
    51. return
    52. });
    53. });
    54. });
    55. }).catch(function (err) {
    56. console.error('Failed to get object: %j', err);
    57. callback(err);
    58. return
    59. });
    60. };
    1. # -*- coding: utf-8 -*-
    2. import oss2, json
    3. from wand.image import Image
    4. def resize(event, context):
    5. evt = json.loads(event)
    6. creds = context.credentials
    7. # Required by OSS sdk
    8. auth=oss2.StsAuth(
    9. creds.access_key_id,
    10. creds.access_key_secret,
    11. creds.security_token)
    12. evt = evt['events'][0]
    13. bucket_name = evt['oss']['bucket']['name']
    14. endpoint = 'oss-' + evt['region'] + '.aliyuncs.com'
    15. bucket = oss2.Bucket(auth, endpoint, bucket_name)
    16. objectName = evt['oss']['object']['key']
    17. # Processed images will be saved to processed/
    18. newKey = objectName.replace("source/", "processed/")
    19. remote_stream = bucket.get_object(objectName)
    20. if not remote_stream:
    21. return
    22. remote_stream = remote_stream.read()
    23. with Image(blob=remote_stream) as img:
    24. with img.clone() as i:
    25. i.resize(128, 128)
    26. new_blob = i.make_blob()
    27. bucket.put_object(newKey, new_blob)
    1. <?php
    2. use OSS\OssClient;
    3. function resize($event, $context) {
    4. $event = json_decode($event, $assoc = true);
    5. $accessKeyId = $context["credentials"]["accessKeyId"];
    6. $accessKeySecret = $context["credentials"]["accessKeySecret"];
    7. $securityToken = $context["credentials"]["securityToken"];
    8. $evt = $event['events'][0];
    9. $bucketName = $evt['oss']['bucket']['name'];
    10. $endpoint = 'oss-' . $evt['region'] . '.aliyuncs.com';
    11. $objectName = $evt['oss']['object']['key'];
    12. $newKey = str_replace("source/", "processed/", $objectName);
    13. try {
    14. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken);
    15. $content = $ossClient->getObject($objectName);
    16. if ($content == null || $content == "") {
    17. return;
    18. }
    19. $imagick = new Imagick();
    20. $imagick->readImageBlob($content);
    21. $imagick->resizeImage(128, 128, Imagick::FILTER_LANCZOS, 1);
    22. $ossClient->putObject($bucketName, $newKey, $imagick->getImageBlob());
    23. } catch (OssException $e) {
    24. print($e->getMessage());
    25. }
    26. }

下一步

步骤三:测试函数