ysugimoto / aws-lambda-image

Automatic image resize/reduce on AWS Lambda
MIT License
824 stars 219 forks source link

Replace original images with reduced and resized image #206

Open glassdimlygr opened 4 years ago

glassdimlygr commented 4 years ago

I'd like to back up and then replace the originals with a new file that has been both reduced and resized.

From the way this lambda is written, I can't seem to do that, seeing as, from comments, it can't output to the same directory.

I am thinking about creating two lambdas to watch two processing folders, then moving the image over the original.

glassdimlygr commented 4 years ago

I created two lambdas, the first with a reduce task that watches /mysubdir/.jpg (for a simplified example) and moves it to /reduced/

{
    "bucket": "mybucket",
    "backup": {
        "directory": "./original"
    },
    "keepExtension": true,
    "reduce": {
        "directory": "reduced",
        "quality": 70,
        "acl": "public-read",
        "cacheControl": "public, max-age=31536000"
    },
    "optimizers": {
        "pngquant": ["--speed=1", "--quality=60-90"],
        "mozjpeg": ["-optimize", "-progressive"],
        "gifsicle": ["-O3"]
    }
}

The second watches reduced/.jpg, resizes, and then moves to /mysubdir/, resizing to 100px max width (for example)

{
  "bucket": "mybucket",
  "keepExtension": true,
  "resizes": [
    {
      "size": "100x8000>",
      "directory": "test",
      "cacheControl": null
    }
  ]
}

In order to replace the original image, it has to be done like that. I had lots of problems with overlapping event paths because Amazon doesn't allow for exclusions or wildcards in the path of events.

But this works well enough. The only code change I had to make was in lib/S3FileSystem.js where I removed at line 24:

                if ( "img-processed" in data.Metadata ) {
                    reject("Object was already processed.");
                } else 

I instead of looking for img-processed, I think this code ought to write and check for the ARN of the lambda. Normally I would make a PR, but I have to roll on.

I also think a great improvement would be allowing events to chain. I feel like this library is great, but ultimately one wants an image that is both resized and reduced in the end--if one wants to resize it at all.

It would also be great if the original file could be replaced. For instance, we return a URL to users after they upload their file, so we have to replace the original.