Preparations:
- Run the following commands in the terminal to create the package.json file and install the jimp module.
// Create the package.json file.
npm init
// Install the jimp module.
npm install jimp
- Make sure that the handler of the function is index.handler.
Sample code:
'use strict';
console.log('Loading function ...');
var oss = require('ali-oss').Wrapper;
var fs = require('fs');
var jimp = require("jimp");
module.exports.handler = function (eventBuf, ctx, callback) {
console.log('Received event:', eventBuf.toString());
var event = JSON.parse(eventBuf);
var ossEvent = event.events[0];
// Required by OSS sdk: OSS region is prefixed with "oss-", e.g. "oss-cn-shanghai"
var ossRegion = "oss-" + ossEvent.region;
// Create oss client.
var client = new oss({
region: ossRegion,
// Credentials can be retrieved from context
accessKeyId: ctx.credentials.accessKeyId,
accessKeySecret: ctx.credentials.accessKeySecret,
stsToken: ctx.credentials.securityToken
});
// Bucket name is from OSS event
client.useBucket(ossEvent.oss.bucket.name);
// Processed images will be saved to processed/
var newKey = ossEvent.oss.object.key.replace("source/", "processed/");
var tmpFile = "/tmp/processed.png";
// Get object
console.log('Getting object: ', ossEvent.oss.object.key)
client.get(ossEvent.oss.object.key).then(function (val) {
// Read object from buffer
jimp.read(val.content, function (err, image) {
if (err) {
console.error("Failed to read image");
callback(err);
return;
}
// Resize the image and save it to a tmp file
image.resize(128, 128).write(tmpFile, function (err) {
if (err) {
console.error("Failed to write image locally");
callback(err);
return;
}
// Putting object back to OSS with the new key
console.log('Putting object: ', newKey);
client.put(newKey, tmpFile).then(function (val) {
console.log('Put object:', val);
callback(null, val);
return;
}).catch(function (err) {
console.error('Failed to put object: %j', err);
callback(err);
return
});
});
});
}).catch(function (err) {
console.error('Failed to get object: %j', err);
callback(err);
return
});
};
Preparations:
- Make sure that the RAM role configured for the Function Compute service to which the function belongs has the permissions to access OSS. You can log on to the Resource Access Management console to grant the RAM role the permissions to access OSS.
- Make sure that the handler of the function is index.handler.
Sample code:
# -*- coding: utf-8 -*-
import oss2, json
from wand.image import Image
def handler(event, context):
evt = json.loads(event)
creds = context.credentials
# Required by OSS sdk
auth=oss2.StsAuth(
creds.access_key_id,
creds.access_key_secret,
creds.security_token)
evt = evt['events'][0]
bucket_name = evt['oss']['bucket']['name']
endpoint = 'oss-' + evt['region'] + '.aliyuncs.com'
bucket = oss2.Bucket(auth, endpoint, bucket_name)
objectName = evt['oss']['object']['key']
# Processed images will be saved to processed/
newKey = objectName.replace("source/", "processed/")
remote_stream = bucket.get_object(objectName)
if not remote_stream:
return
remote_stream = remote_stream.read()
with Image(blob=remote_stream) as img:
with img.clone() as i:
i.resize(128, 128)
new_blob = i.make_blob()
bucket.put_object(newKey, new_blob)
Preparations:
- Make sure that the RAM role configured for the Function Compute service to which the function belongs has the permissions to access OSS. You can log on to the RAM console to grant the RAM role the permissions to access OSS.
- Make sure that the handler of the function is index.handler.
Sample code:
<?php
use OSS\OssClient;
function handler($event, $context) {
$event = json_decode($event, $assoc = true);
$accessKeyId = $context["credentials"]["accessKeyId"];
$accessKeySecret = $context["credentials"]["accessKeySecret"];
$securityToken = $context["credentials"]["securityToken"];
$evt = $event['events'][0];
$bucketName = $evt['oss']['bucket']['name'];
$endpoint = 'oss-' . $evt['region'] . '.aliyuncs.com';
$objectName = $evt['oss']['object']['key'];
$newKey = str_replace("source/", "processed/", $objectName);
try {
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken);
$content = $ossClient->getObject($bucketName , $objectName);
if ($content == null || $content == "") {
return;
}
$imagick = new Imagick();
$imagick->readImageBlob($content);
$imagick->resizeImage(128, 128, Imagick::FILTER_LANCZOS, 1);
$ossClient->putObject($bucketName, $newKey, $imagick->getImageBlob());
} catch (OssException $e) {
print($e->getMessage());
}
}
Preparations:
- Add the following dependencies to the pom.xml file.
<dependencies>
<dependency>
<groupId>com.aliyun.fc.runtime</groupId>
<artifactId>fc-java-core</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>com.aliyun.fc.runtime</groupId>
<artifactId>fc-java-event</artifactId>
<version>1.2.0</version>
</dependency>
</dependencies>
- Make sure that the handler of the function is example.App::handleRequest.
Sample code:
package example;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.StreamRequestHandler;
import com.aliyun.fc.runtime.event.OSSEvent;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class App implements StreamRequestHandler {
private static final ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
@Override
public void handleRequest(
InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
OSSEvent ossEvent = mapper.readValue(inputStream, new TypeReference<OSSEvent>() {});
for (OSSEvent.Event event : ossEvent.events) {
outputStream.write(String.format("received %s from %s @ %s", event.eventName, event.eventSource, event.region).getBytes());
outputStream.write(String.format("received bucket %s", event.oss.bucket.arn).getBytes());
outputStream.write(String.format("received object %s and it's size is %s", event.oss.object.key, event.oss.object.size).getBytes());
}
}
}