Azure Functionsを利用した画像サムネイル自動生成
2017年 12月 07日
こんにちは、ブログ技術セクション エンジニアの鈴木です。
本日はエキサイトブログで幅広く活用させていただいている Microsoft Azure の中から個人的に気になっているAzure Functionsを利用して、Azure Storageにアップロードした画像のサムネイルを自動生成するという小ネタを書きたいと思います。
Azure Functionsとは
小規模な関数をマネージド環境で手軽に実行できるサービスです。
いわゆるサーバレスといわれるもので下記が類似のサービスとなります。(今回これらのサービスとの比較は割愛します)
- AWS lambda
- Google Cloud Functions
サムネイル自動生成までの手順
では実際にAzure Functionsでサムネイル自動生成する関数を作っていきたいと思います。


(いつまでたっても返ってこない場合は、ローカルでnpm installした後、node_modulesをZIP圧縮してドロップ)
package.json
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"azure-imagemagick": "^0.4.2"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
これで下地はできたのであとはコードをガシガシ書いていきます。(対して書かない)

function.json
{
"bindings": [
{
"name": "inputBlob",
"type": "blobTrigger",
"direction": "in",
"dataType": "binary",
"path": "samples-workitems/{name}.{extension}",
"connection": "AzureWebJobsDashboard"
},
{
"name": "outputBlob",
"type": "blob",
"direction": "out",
"dataType": "binary",
"path": "samples-resultitems/{name}.{extension}",
"connection": "AzureWebJobsDashboard"
}
],
"disabled": false
}
指定にマッチするファイル(samples-resultitems/{name}.{extension})がアップロードされたら、
この関数で処理をして、指定のパス(samples-resultitems/{name}.{extension})へ出力します。

index.js
const axios = require('axios');
const im = require('azure-imagemagick');
module.exports = function (context) {
if (!context.bindings.inputBlob) {
context.done();
}
im.resize({
srcData: context.bindings.inputBlob,
width: 200
}, function(err, stdout, stderr){
if (err) context.log.error(err);
context.bindings.outputBlob = stdout;
context.done();
});
};