-
Notifications
You must be signed in to change notification settings - Fork 1
Fix Various Resizing Issues #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,160 +1,160 @@ | ||
| /********************************************************************************************************************* | ||
| * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * | ||
| * * | ||
| * Licensed under the Amazon Software License (the "License"). You may not use this file except in compliance * | ||
| * with the License. A copy of the License is located at * | ||
| * * | ||
| * http://aws.amazon.com/asl/ * | ||
| * * | ||
| * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * | ||
| * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions * | ||
| * and limitations under the License. * | ||
| *********************************************************************************************************************/ | ||
| const AWS = require('aws-sdk'); | ||
| const sharp = require('sharp'); | ||
| class ImageHandler { | ||
| /** | ||
| * Main method for processing image requests and outputting modified images. | ||
| * @param {ImageRequest} request - An ImageRequest object. | ||
| */ | ||
| async process(request) { | ||
| const originalImage = request.originalImage; | ||
| const edits = request.edits; | ||
| if (edits !== undefined) { | ||
| const modifiedImage = await this.applyEdits(originalImage, edits); | ||
| if (request.outputFormat !== undefined) { | ||
| await modifiedImage.toFormat(request.outputFormat); | ||
| } | ||
| const bufferImage = await modifiedImage.toBuffer(); | ||
| return bufferImage.toString('base64'); | ||
| } else { | ||
| return originalImage.toString('base64'); | ||
| } | ||
| } | ||
| /** | ||
| * Applies image modifications to the original image based on edits | ||
| * specified in the ImageRequest. | ||
| * @param {Buffer} originalImage - The original image. | ||
| * @param {Object} edits - The edits to be made to the original image. | ||
| */ | ||
| async applyEdits(originalImage, edits) { | ||
| const image = sharp(originalImage); | ||
| const keys = Object.keys(edits); | ||
| const values = Object.values(edits); | ||
| // Apply the image edits | ||
| for (let i = 0; i < keys.length; i++) { | ||
| const key = keys[i]; | ||
| const value = values[i]; | ||
| if (key === 'overlayWith') { | ||
| const overlay = await this.getOverlayImage(value.bucket, value.key); | ||
| image.overlayWith(overlay, value.options); | ||
| } else if (key === 'smartCrop') { | ||
| /********************************************************************************************************************* | ||
| * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * | ||
| * * | ||
| * Licensed under the Amazon Software License (the "License"). You may not use this file except in compliance * | ||
| * with the License. A copy of the License is located at * | ||
| * * | ||
| * http://aws.amazon.com/asl/ * | ||
| * * | ||
| * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * | ||
| * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions * | ||
| * and limitations under the License. * | ||
| *********************************************************************************************************************/ | ||
|
|
||
| const AWS = require('aws-sdk'); | ||
| const sharp = require('sharp'); | ||
|
|
||
| class ImageHandler { | ||
|
|
||
| /** | ||
| * Main method for processing image requests and outputting modified images. | ||
| * @param {ImageRequest} request - An ImageRequest object. | ||
| */ | ||
| async process(request) { | ||
| const originalImage = request.originalImage; | ||
| const edits = request.edits; | ||
| if (edits !== undefined) { | ||
| const modifiedImage = await this.applyEdits(originalImage, edits); | ||
| if (request.outputFormat !== undefined) { | ||
| await modifiedImage.toFormat(request.outputFormat); | ||
| } | ||
| const bufferImage = await modifiedImage.toBuffer(); | ||
| return bufferImage.toString('base64'); | ||
| } else { | ||
| return originalImage.toString('base64'); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Applies image modifications to the original image based on edits | ||
| * specified in the ImageRequest. | ||
| * @param {Buffer} originalImage - The original image. | ||
| * @param {Object} edits - The edits to be made to the original image. | ||
| */ | ||
| async applyEdits(originalImage, edits) { | ||
| const image = sharp(originalImage, { failOnError: false }).rotate(); | ||
| const keys = Object.keys(edits); | ||
| const values = Object.values(edits); | ||
| // Apply the image edits | ||
| for (let i = 0; i < keys.length; i++) { | ||
| const key = keys[i]; | ||
| const value = values[i]; | ||
| if (key === 'overlayWith') { | ||
| const overlay = await this.getOverlayImage(value.bucket, value.key); | ||
| image.overlayWith(overlay, value.options); | ||
| } else if (key === 'smartCrop') { | ||
| const options = value; | ||
| const imageBuffer = await image.toBuffer(); | ||
| const metadata = await image.metadata(); | ||
| // ---- | ||
| const boundingBox = await this.getBoundingBox(imageBuffer, options.faceIndex); | ||
| const cropArea = await this.getCropArea(boundingBox, options, metadata); | ||
| try { image.extract(cropArea) } | ||
| const boundingBox = await this.getBoundingBox(imageBuffer, options.faceIndex); | ||
| const cropArea = await this.getCropArea(boundingBox, options, metadata); | ||
| try { image.extract(cropArea) } | ||
| catch (err) { | ||
| throw ({ | ||
| status: 400, | ||
| code: 'SmartCrop::PaddingOutOfBounds', | ||
| message: 'The padding value you provided exceeds the boundaries of the original image. Please try choosing a smaller value or applying padding via Sharp for greater specificity.' | ||
| }); | ||
| } | ||
| } else { | ||
| image[key](value); | ||
| } | ||
| } | ||
| // Return the modified image | ||
| return image; | ||
| } | ||
| /** | ||
| * Gets an image to be used as an overlay to the primary image from an | ||
| * Amazon S3 bucket. | ||
| * @param {string} bucket - The name of the bucket containing the overlay. | ||
| * @param {string} key - The keyname corresponding to the overlay. | ||
| */ | ||
| async getOverlayImage(bucket, key) { | ||
| const s3 = new AWS.S3(); | ||
| const params = { Bucket: bucket, Key: key }; | ||
| // Request | ||
| const request = s3.getObject(params).promise(); | ||
| // Response handling | ||
| try { | ||
| const overlayImage = await request; | ||
| return Promise.resolve(overlayImage.Body); | ||
| } catch (err) { | ||
| return Promise.reject({ | ||
| status: 500, | ||
| code: err.code, | ||
| message: err.message | ||
| }) | ||
| } | ||
| } | ||
| /** | ||
| } else { | ||
| image[key](value); | ||
| } | ||
| } | ||
| // Return the modified image | ||
| return image; | ||
| } | ||
|
|
||
| /** | ||
| * Gets an image to be used as an overlay to the primary image from an | ||
| * Amazon S3 bucket. | ||
| * @param {string} bucket - The name of the bucket containing the overlay. | ||
| * @param {string} key - The keyname corresponding to the overlay. | ||
| */ | ||
| async getOverlayImage(bucket, key) { | ||
| const s3 = new AWS.S3(); | ||
| const params = { Bucket: bucket, Key: key }; | ||
| // Request | ||
| const request = s3.getObject(params).promise(); | ||
| // Response handling | ||
| try { | ||
| const overlayImage = await request; | ||
| return Promise.resolve(overlayImage.Body); | ||
| } catch (err) { | ||
| return Promise.reject({ | ||
| status: 500, | ||
| code: err.code, | ||
| message: err.message | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Calculates the crop area for a smart-cropped image based on the bounding | ||
| * box data returned by Amazon Rekognition, as well as padding options and | ||
| * the image metadata. | ||
| * @param {Object} boundingBox - The boudning box of the detected face. | ||
| * @param {Object} options - Set of options for smart cropping. | ||
| * @param {Object} boundingBox - The boudning box of the detected face. | ||
| * @param {Object} options - Set of options for smart cropping. | ||
| * @param {Object} metadata - Sharp image metadata. | ||
| */ | ||
| getCropArea(boundingBox, options, metadata) { | ||
| */ | ||
| getCropArea(boundingBox, options, metadata) { | ||
| const padding = (options.padding !== undefined) ? parseFloat(options.padding) : 0; | ||
| // Calculate the smart crop area | ||
| const cropArea = { | ||
| left : parseInt((boundingBox.Left*metadata.width)-padding), | ||
| top : parseInt((boundingBox.Top*metadata.height)-padding), | ||
| width : parseInt((boundingBox.Width*metadata.width)+(padding*2)), | ||
| height : parseInt((boundingBox.Height*metadata.height)+(padding*2)), | ||
| } | ||
| // Return the crop area | ||
| return cropArea; | ||
| } | ||
| /** | ||
| * Gets the bounding box of the specified face index within an image, if specified. | ||
| * @param {Sharp} imageBuffer - The original image. | ||
| * @param {Integer} faceIndex - The zero-based face index value, moving from 0 and up as | ||
| * confidence decreases for detected faces within the image. | ||
| */ | ||
| async getBoundingBox(imageBuffer, faceIndex) { | ||
| const rekognition = new AWS.Rekognition(); | ||
| const params = { Image: { Bytes: imageBuffer }}; | ||
| // Calculate the smart crop area | ||
| const cropArea = { | ||
| left : parseInt((boundingBox.Left*metadata.width)-padding), | ||
| top : parseInt((boundingBox.Top*metadata.height)-padding), | ||
| width : parseInt((boundingBox.Width*metadata.width)+(padding*2)), | ||
| height : parseInt((boundingBox.Height*metadata.height)+(padding*2)), | ||
| } | ||
| // Return the crop area | ||
| return cropArea; | ||
| } | ||
|
|
||
| /** | ||
| * Gets the bounding box of the specified face index within an image, if specified. | ||
| * @param {Sharp} imageBuffer - The original image. | ||
| * @param {Integer} faceIndex - The zero-based face index value, moving from 0 and up as | ||
| * confidence decreases for detected faces within the image. | ||
| */ | ||
| async getBoundingBox(imageBuffer, faceIndex) { | ||
| const rekognition = new AWS.Rekognition(); | ||
| const params = { Image: { Bytes: imageBuffer }}; | ||
| const faceIdx = (faceIndex !== undefined) ? faceIndex : 0; | ||
| // Request | ||
| const request = rekognition.detectFaces(params).promise(); | ||
| // Response handling | ||
| try { | ||
| // Request | ||
| const request = rekognition.detectFaces(params).promise(); | ||
| // Response handling | ||
| try { | ||
| const response = (await request).FaceDetails[faceIdx].BoundingBox; | ||
| return Promise.resolve(await response); | ||
| } catch (err) { | ||
| console.log(err); | ||
| return Promise.resolve(await response); | ||
| } catch (err) { | ||
| console.log(err); | ||
| if (err.message === "Cannot read property 'BoundingBox' of undefined") { | ||
| return Promise.reject({ | ||
| return Promise.reject({ | ||
| status: 400, | ||
| code: 'SmartCrop::FaceIndexOutOfRange', | ||
| message: 'You have provided a FaceIndex value that exceeds the length of the zero-based detectedFaces array. Please specify a value that is in-range.' | ||
| }) | ||
| }) | ||
| } else { | ||
| return Promise.reject({ | ||
| status: 500, | ||
| code: err.code, | ||
| message: err.message | ||
| }) | ||
| return Promise.reject({ | ||
| status: 500, | ||
| code: err.code, | ||
| message: err.message | ||
| }) | ||
| } | ||
| } | ||
| } | ||
| } | ||
| // Exports | ||
| module.exports = ImageHandler; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Exports | ||
| module.exports = ImageHandler; | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,7 +14,7 @@ | |
| const ThumborMapping = require('./thumbor-mapping'); | ||
|
|
||
| class ImageRequest { | ||
|
|
||
| /** | ||
| * Initializer function for creating a new image request, used by the image | ||
| * handler to perform image modifications. | ||
|
|
@@ -136,9 +136,7 @@ class ImageRequest { | |
| const decoded = this.decodeRequest(event); | ||
| return decoded.key; | ||
| } else if (requestType === "Thumbor" || requestType === "Custom") { | ||
| // Parse the key from the end of the path | ||
| const key = (event["path"]).split("/"); | ||
| return key[key.length - 1]; | ||
| return decodeURIComponent(event["path"].replace(/\d+x\d+\/|filters[:-][^/;]+|\/fit-in\/+|^\/+/g, '').replace(/^\/+/, '')); | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Changed There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. That's different from my fix in aws-manage, I'm wondering if it's more or less robust 🤔 Mine is very tied to our usage, I take the path coming after the last |
||
| } else { | ||
| // Return an error for all other conditions | ||
| throw ({ | ||
|
|
@@ -151,7 +149,7 @@ class ImageRequest { | |
|
|
||
| /** | ||
| * Determines how to handle the request being made based on the URL path | ||
| * prefix to the image request. Categorizes a request as either "image" | ||
| * prefix to the image request. Categorizes a request as either "image" | ||
| * (uses the Sharp library), "thumbor" (uses Thumbor mapping), or "custom" | ||
| * (uses the rewrite function). | ||
| * @param {Object} event - Lambda request body. | ||
|
|
@@ -160,12 +158,12 @@ class ImageRequest { | |
| const path = event["path"]; | ||
| // ---- | ||
| const matchDefault = new RegExp(/^(\/?)([0-9a-zA-Z+\/]{4})*(([0-9a-zA-Z+\/]{2}==)|([0-9a-zA-Z+\/]{3}=))?$/); | ||
| const matchThumbor = new RegExp(/^(\/?)((fit-in)?|(filters:.+\(.?\))?|(unsafe)?).*(.+jpg|.+png|.+webp|.+tiff|.+jpeg)$/); | ||
| const matchCustom = new RegExp(/(\/?)(.*)(jpg|png|webp|tiff|jpeg)/); | ||
| const matchThumbor = new RegExp(/^(\/?)((fit-in)?|(filters:.+\(.?\))?|(unsafe)?).*(.+jpg|.+png|.+webp|.+tiff|.+jpeg)$/i); | ||
| const matchCustom = new RegExp(/(\/?)(.*)(jpg|png|webp|tiff|jpeg)/i); | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. These 2 lines changed |
||
| const definedEnvironmentVariables = ( | ||
| (process.env.REWRITE_MATCH_PATTERN !== "") && | ||
| (process.env.REWRITE_SUBSTITUTION !== "") && | ||
| (process.env.REWRITE_MATCH_PATTERN !== undefined) && | ||
| (process.env.REWRITE_MATCH_PATTERN !== "") && | ||
| (process.env.REWRITE_SUBSTITUTION !== "") && | ||
| (process.env.REWRITE_MATCH_PATTERN !== undefined) && | ||
| (process.env.REWRITE_SUBSTITUTION !== undefined) | ||
| ); | ||
| // ---- | ||
|
|
@@ -214,7 +212,7 @@ class ImageRequest { | |
| } | ||
|
|
||
| /** | ||
| * Returns a formatted image source bucket whitelist as specified in the | ||
| * Returns a formatted image source bucket whitelist as specified in the | ||
| * SOURCE_BUCKETS environment variable of the image handler Lambda | ||
| * function. Provides error handling for missing/invalid values. | ||
| */ | ||
|
|
@@ -235,4 +233,4 @@ class ImageRequest { | |
| } | ||
|
|
||
| // Exports | ||
| module.exports = ImageRequest; | ||
| module.exports = ImageRequest; | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,7 +10,7 @@ | |
| "license": "ISC", | ||
| "dependencies": { | ||
| "mocha": "^6.1.4", | ||
| "sharp": "^0.21.3", | ||
| "sharp": "^0.22.1", | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Changed |
||
| "sinon": "^7.3.2", | ||
| "nyc": "^14.0.0" | ||
| }, | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Changed
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why was the call to
.rotate()added?