AWS Lambdaサンプル スクリプトを活用して、Node.js と ImageMagick/GraphicsMagick ライブラリを使用して JPG 画像のサイズを変更しています。サイズ変更後に画像をJPGからWebP形式に変換する簡単な変更を加えたいと思います。(GraphicsMagick は WebP をサポートしていませんが、スクリプトでサブクラス化されている ImageMagick はサポートしています)。これは、こちらのBuffersセクションの例(JPG を PNG に変換する)のように、次のコード ブロックで可能になります。
gm('img.jpg')
.resize(100, 100)
.toBuffer('PNG',function (err, buffer) {
if (err) return handle(err);
console.log('done!');
})
ローカルの Node.js インストールでそのコード ブロックを実行すると (PNG を WebP に置き換えます)、動作します。
ただし、AWS Lambdaサンプル スクリプトの変換関数 (以下を参照) を変更してAWS で実行すると、次の「ストリームが空のバッファーを生成します」というエラーが表示されます。
Unable to resize mybucket/104A0378.jpg and upload to mybucket_resized/resized-104A0378.jpg due to an error: Error: Stream yields empty buffer
変更された transform() 関数 (「webp」のある行を参照):
function tranform(response, next) {
gm(response.Body).size(function(err, size) {
// Infer the scaling factor to avoid stretching the image unnaturally.
var scalingFactor = Math.min(
MAX_WIDTH / size.width,
MAX_HEIGHT / size.height
);
var width = scalingFactor * size.width;
var height = scalingFactor * size.height;
// Transform the image buffer in memory.
this.resize(width, height)
.toBuffer('webp', function(err, buffer) {
if (err) {
next(err);
} else {
next(null, response.ContentType, buffer);
}
});
});
}
response.ContentType はまだ image/jpeg と同じですが、ここで役割を果たしているとは思いません。また、サイズを変更する前におそらく WebP に変換する必要があることに気付きましたが、一歩一歩!
何か案は?