#はじめに
S3のある一つのバケットに保存している全ての画像のサムネイルを生成したいと思っています
#問題
AWS Lambdaを使用して、下記のような関数を作成しました。
var async = require('async'); var AWS = require('aws-sdk'); var gm = require('gm').subClass({ imageMagick: true }); // Enable ImageMagick integration. var util = require('util'); var path = require('path'); // get reference to S3 client var s3 = new AWS.S3(); exports.handler = function(event, context) { var bucket = "develop-hoge-files"; var items = []; var params = { Bucket: bucket, Prefix: "images/" }; //S3対象のバケット内の画像を全て取得 s3.listObjects(params, function(err, data) { if (err) console.log(err, err.stack); // an error occurred else for (var i = 0; i < data.Contents.length; i++) { if (data.Contents[i].Key.match(".jpeg") && data.Contents[i].Key.match("images/")) { //コールバックで返ってきたデータを使用して、画像のキーを取得し、画像のリサイズとその画像を任意のバケットにアップロードする関数を呼び出す imageResizeUpload(data.Contents[i].Key); } } }); }; function imageResizeUpload(key) { async.waterfall([ function download(next) { // Download the image from S3 into a buffer. s3.getObject({ Bucket: "develop-hoge-files", Key: key }, next); }, function transform(response, next) { gm(response.Body).size(function(err, size) { var width = 640; var height = 480; // Transform the image buffer in memory. this.resize(width, height) .toBuffer("jpeg", function(err, buffer) { if (err) { next(err); } else { next(null, response.ContentType, buffer); } }); }); }, function upload(contentType, data, next) { // Stream the transformed image to a different S3 bucket. s3.putObject({ Bucket: "develop-hoge-files", Key: key.replace("images","test-thumbnail-images"), Body: data, ContentType: contentType }, next); } ], function (err) { if (err) { console.log("error"); } else { console.log("success"); } } ); }
バケット内に画像が200枚ほど存在していまして、それを一つ一つ変換し任意のバケットにアップロードしていきたいのですが、そこの処理をどのように工夫すればいまいちピンとこず。
画像のリサイズから変換に時間を要するので、それが終わった瞬間に次の処理に移るといった書き方が知りたいです。
具体的に変換を行なっているコードは以下の部分です。 imageResizeUpload
関数で、リサイズとアップロードを行なっています。
for (var i = 0; i < data.Contents.length; i++) { if (data.Contents[i].Key.match(".jpeg") && data.Contents[i].Key.match("images/")) { //コールバックで返ってきたデータを使用して、画像のキーを取得し、画像のリサイズとその画像を任意のバケットにアップロードする関数を呼び出す imageResizeUpload(data.Contents[i].Key); } }
どなたかアドバイスできる方いらっしゃいましたら、お願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/01/10 02:56