├── .gitignore ├── index.js ├── webpack.fly.config.js ├── package.json ├── README.md ├── src ├── cache.ts └── images.ts ├── tsconfig.json └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .fly 2 | node_modules 3 | lib 4 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import { processImages } from './src/images' 2 | import backends from 'onehostname/lib/backends' 3 | 4 | const origin = backends.generic("https://blog.ghost.org", { host: "blog.ghost.org" }) 5 | 6 | const processor = processImages(origin, { detectWebp: true }) 7 | 8 | fly.http.respondWith(processor) -------------------------------------------------------------------------------- /webpack.fly.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | entry: "./index.js", 3 | resolve: { 4 | // Add `.ts` and `.tsx` as a resolvable extension. 5 | extensions: [".ts", ".tsx", ".js"] 6 | }, 7 | module: { 8 | rules: [ 9 | // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader` 10 | { test: /\.tsx?$/, use: ["ts-loader"] } 11 | ] 12 | } 13 | }; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "image-processing", 3 | "version": "0.1.0", 4 | "description": "Fly image processing Edge Application", 5 | "main": "index.js", 6 | "scripts": { 7 | "start": "npx fly server", 8 | "test": "npx fly test", 9 | "prepublishOnly": "tsc" 10 | }, 11 | "repository": { 12 | "type": "git", 13 | "url": "git+https://github.com/superfly/image-processing.git" 14 | }, 15 | "keywords": [ 16 | "image-processing", 17 | "optimization", 18 | "png", 19 | "jpg", 20 | "cdn" 21 | ], 22 | "author": "Kurt Mackey", 23 | "license": "Apache-2.0", 24 | "bugs": { 25 | "url": "https://github.com/superfly/image-processing/issues" 26 | }, 27 | "homepage": "https://github.com/superfly/image-processing#readme", 28 | "devDependencies": { 29 | "@fly/fly": "^0.28.4", 30 | "@types/color": "^3.0.0", 31 | "color": "^3.0.0", 32 | "onehostname": "^0.1.1", 33 | "ts-loader": "^3.5.0", 34 | "typescript": "^2.8.1" 35 | } 36 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Fly Image Processing App 2 | 3 | To run: 4 | * Clone this repository 5 | * `npm install` (Need recent node version) 6 | * `npm start` 7 | 8 | Demo URLs: 9 | * http://localhost:3000/content/images/2018/01/ghostzapimg--3-.jpg?w_url=/assets/img/ghostpro.svg&w_pos=southwest&w_pad=10%25&w_w=20%25&w_bg=rgba(128,128,255,0.5) 10 | * http://localhost:3000/content/images/2018/01/ghostzapimg--3-.jpg?w_url=/assets/img/ghostpro.svg&w_pos=northeast&w_pad=10%25&w_w=20%25&w_bg=rgba(255,128,128,0.5) 11 | 12 | ## URL options 13 | 14 | ##### Image 15 | * Size: leave either of these blank to auto scale a dimension 16 | * **`w`**: Width in pixels or percent (`200`, `200px`, `50%`) 17 | * **`h`**: Height in pixels or percent (`140`, `140px`, `50%`) 18 | * **`f`**: desired output format 19 | ##### Watermark 20 | * **`w_url`**: URL to the watermark image (like `/watermarks/blah.png`) 21 | * **`w_bg`**: Background color for watermark (like `transparent` or `rgba(128,128,0,0.5)`) 22 | * **`w_pos`**: Watermark Position: `north`, `south`, `east`, `west` ... 23 | * **`w_pad`**: padding around watermark. If a bg color is specified, padding expands the colored canvas 24 | 25 | -------------------------------------------------------------------------------- /src/cache.ts: -------------------------------------------------------------------------------- 1 | interface fly { 2 | cache: { 3 | get: (key: string) => Promise, 4 | getString: (key: string) => Promise, 5 | set: (key: string, value: ArrayBuffer | string, ttl?: number) => Promise 6 | } 7 | } 8 | declare var fly: fly 9 | // TODO: Make `getImage` a thing in Fly 10 | export async function get(key: string) { 11 | const raw = await fly.cache.getString(key + ":meta") 12 | if (!raw) { 13 | return null 14 | } 15 | let meta = null 16 | try { 17 | meta = JSON.parse(raw) 18 | } catch (err) { 19 | return null 20 | } 21 | 22 | const body = await fly.cache.get(key + ":body") 23 | 24 | if (!body) { return null } 25 | return new Response(body, meta) 26 | } 27 | 28 | export async function set(key: string, resp: Response, ttl?: number) { 29 | const headers: any = resp.headers 30 | const meta = { 31 | status: resp.status, 32 | headers: headers.toJSON() // fly specific function 33 | } 34 | 35 | const body = await resp.arrayBuffer() 36 | const result = await Promise.all([ 37 | fly.cache.set(key + ":meta", JSON.stringify(meta), ttl), 38 | fly.cache.set(key + ":body", body, ttl) 39 | ]) 40 | 41 | for (const r of result) { 42 | if (!r) return false 43 | } 44 | return true 45 | } 46 | 47 | export default { 48 | get, 49 | set 50 | } -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": [ 3 | "./src/**/*.ts" 4 | ], 5 | "compilerOptions": { 6 | /* Basic Options */ 7 | "target": "es2015", 8 | /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */ 9 | "module": "commonjs", 10 | /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ 11 | // "lib": [], /* Specify library files to be included in the compilation: */ 12 | "lib": [ 13 | "es2017", 14 | "dom" 15 | ], 16 | // "allowJs": true, 17 | /* Allow javascript files to be compiled. */ 18 | // "checkJs": true, /* Report errors in .js files. */ 19 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 20 | "declaration": true, /* Generates corresponding '.d.ts' file. */ 21 | // "sourceMap": true, 22 | /* Generates corresponding '.map' file. */ 23 | // "outFile": "./", /* Concatenate and emit output to single file. */ 24 | "outDir": "./lib", /* Redirect output structure to the directory. */ 25 | // "rootDir": ".", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 26 | // "removeComments": true, /* Do not emit comments to output. */ 27 | // "noEmit": true, /* Do not emit outputs. */ 28 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 29 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 30 | // "isolatedModules": false, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 31 | /* Strict Type-Checking Options */ 32 | "strict": true, 33 | /* Enable all strict type-checking options. */ 34 | "noImplicitAny": true, 35 | /* Raise error on expressions and declarations with an implied 'any' type. */ 36 | // "strictNullChecks": true, /* Enable strict null checks. */ 37 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 38 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 39 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 40 | /* Additional Checks */ 41 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 42 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 43 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 44 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 45 | /* Module Resolution Options */ 46 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 47 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 48 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 49 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 50 | // "typeRoots": [], /* List of folders to include type definitions from. */ 51 | // "types": [], /* Type declaration files to be included in compilation. */ 52 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 53 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 54 | /* Source Map Options */ 55 | // "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 56 | // "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */ 57 | "inlineSourceMap": true, 58 | /* Emit a single file with source maps instead of having a separate file. */ 59 | "inlineSources": true /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 60 | /* Experimental Options */ 61 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 62 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 63 | } 64 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/images.ts: -------------------------------------------------------------------------------- 1 | import respCache from "./cache"; 2 | import * as Color from 'color' 3 | 4 | declare var fly: any 5 | declare var crypto: any 6 | declare var cache: any // web api cache 7 | export interface Fetch { 8 | (req: RequestInfo, info?: RequestInit): Promise 9 | } 10 | 11 | export interface ProcessOptions { 12 | detectWebp?: boolean 13 | } 14 | 15 | export function processImages(fetch: Fetch, opts?: ProcessOptions): Fetch { 16 | if (!opts) { 17 | opts = { 18 | detectWebp: true 19 | } 20 | } 21 | // A fetch like function to handle image processing 22 | const processImagesFetch = async function processImages(req: RequestInfo, info?: RequestInit) { 23 | if (typeof req === "string") { 24 | req = new Request(req) 25 | } 26 | const url = new URL(req.url) 27 | const params = buildOptions(req, url) 28 | console.debug("params:", params) 29 | 30 | const key = cacheKey(url, params) 31 | let resp = await respCache.get(key + "asdf") 32 | 33 | if (resp) { 34 | resp.headers.set("cache", "HIT") 35 | return resp 36 | } // already done, cached, etc 37 | 38 | req.headers.delete("accept-encoding") // make sure we don't get gzip 39 | 40 | // this is a little hacky, but it caches the master with normal http caching 41 | resp = await cache.match(req) 42 | if (!resp) { 43 | resp = await fetch(req, info) 44 | 45 | cache.put(req, resp.clone()) 46 | } 47 | console.log("Watermark url:", params.watermark && params.watermark.url) 48 | let wresp = params.watermark ? await fetch(new Request(params.watermark.url)) : null 49 | let contentType = resp.headers.get("content-type") || "" 50 | if (resp.status != 200 || !contentType.includes("image/")) { 51 | // not an image, pass through 52 | return resp 53 | } 54 | if (wresp) { 55 | contentType = wresp.headers.get("content-type") || "" 56 | if (wresp.status != 200 || !contentType.includes("image/")) { 57 | // watermark not found 58 | return new Response("watermark url not found (or not an image)", { status: 500 }) 59 | } 60 | } 61 | 62 | const body = await resp.arrayBuffer() 63 | console.debug("body length:", body.byteLength) 64 | let img = new fly.Image(body) 65 | 66 | // this just applies the ops to the image without actually writing it out 67 | img = await resize(img, params) 68 | 69 | if (wresp && params.watermark) { 70 | const wbody = await wresp.arrayBuffer() 71 | const wmark = new fly.Image(wbody) 72 | console.debug("watermark loaded:", wbody.byteLength) 73 | const wm = await watermark(img, wmark, params) 74 | img.overlayWith(wm, { gravity: params.watermark.position }) 75 | console.debug("watermark done") 76 | } 77 | if (params.format) { 78 | const fn = img[params.format] 79 | if (fn && typeof fn === "function") { 80 | fn.apply(img) 81 | resp.headers.set("content-type", `image/${params.format}`) 82 | } 83 | } 84 | 85 | const result = await img.toBuffer() 86 | const data = result.data 87 | resp.headers.set("content-length", data.byteLength.toString()) 88 | resp.headers.set("cache", "MISS") 89 | resp.headers.set("cache-key", key) 90 | respCache.set(key, new Response(data, resp), 3600) 91 | return new Response(data, resp) 92 | } 93 | 94 | const buildOptions = function buildOptions(req: Request, url?: URL): ImageOptions { 95 | if (!url) url = new URL(req.url) 96 | const params: ImageOptions = new (defaultImageOptions.constructor)() 97 | /*{ 98 | width: new Unit(url.searchParams.get("w")), 99 | height: new Unit(url.searchParams.get("h")), 100 | format: extractFormat(url.searchParams.get("format")) 101 | }*/ 102 | for (const p of urlParams) { 103 | const v = p.parser(url.searchParams.get(p.param)) 104 | params[p.key] = v 105 | } 106 | const w = url.searchParams.get("w_url") 107 | if (w) { 108 | const wurl = new URL(req.url) 109 | wurl.pathname = w 110 | wurl.search = "" 111 | params.watermark = { 112 | url: wurl.toString(), 113 | width: defaultUnit, 114 | height: defaultUnit 115 | } 116 | for (const p of urlParamsWatermark) { 117 | const v = p.parser(url.searchParams.get(p.param)) 118 | if (p.key !== "url") 119 | params.watermark[p.key] = v 120 | } 121 | } 122 | const accept = req.headers.get("accept") || "" 123 | if (!params.format && opts && opts.detectWebp && accept.includes("image/webp")) { 124 | params.format = "webp" // output to webp if possible 125 | } 126 | return params 127 | } 128 | 129 | return processImagesFetch 130 | } 131 | 132 | 133 | async function watermark(image: any, wmark: any, opts: ImageOptions) { 134 | if (!opts.watermark) { 135 | throw new Error("this shouldn't ever happen, wtf") 136 | } 137 | 138 | const meta = image.metadata() 139 | let wmeta = wmark.metadata() 140 | 141 | // padding expands the canvas and fills it with the background color 142 | let padding = scaleValue(opts.watermark.padding, meta.width) || 0 143 | let width = scaleValue(opts.watermark.width, meta.width) 144 | let height = scaleValue(opts.watermark.height, meta.height) 145 | 146 | if (width || height) { 147 | // resize wmark to requested size 148 | // make sure we're not making an overlay that's bigger than the image 149 | if (width && width > meta.width) { 150 | width = meta.width 151 | padding = 0 152 | } 153 | if (height && height > meta.height) { 154 | height = meta.height 155 | padding = 0 156 | } 157 | wmark = await wmark.withoutEnlargement().resize(width, height).toImage() 158 | wmeta = wmark.metadata() 159 | width = wmeta.width 160 | height = wmeta.height 161 | } 162 | 163 | if (!opts.watermark.background) { 164 | // default to transparent background on watermark 165 | opts.watermark.background = 'transparent' 166 | } 167 | console.debug("watermark: applying bg", opts.watermark.background) 168 | const color = Color(opts.watermark.background || defaultWatermarkOptions.background).object() 169 | if (color.alpha === undefined) { 170 | color.alpha = 1.0 171 | } 172 | 173 | //build a canvas with bg color + padding for watermark 174 | const bg = new fly.Image({ 175 | width: (width || wmeta.width) + padding, 176 | height: (height || wmeta.height) + padding, 177 | background: color, 178 | channels: 4 179 | }).png() 180 | 181 | // do overlay and get arrayBuffer 182 | let buf = await bg.overlayWith(wmark).toBuffer() 183 | 184 | return buf.data 185 | } 186 | async function resize(image: any, opts: ImageOptions) { 187 | if (defaultSizeOptions.equivalent(opts)) { 188 | console.debug("resize noop:", JSON.stringify(opts)) 189 | return image 190 | } 191 | let width: number | undefined 192 | let height: number | undefined 193 | if (opts.width.unit === "px") { 194 | width = opts.width.value 195 | } 196 | if (opts.height.unit === "px") { 197 | height = opts.height.value 198 | } 199 | if (width && !height) { } 200 | console.debug("resizing:", width, height, null) 201 | return await image.resize(width, height).toImage() 202 | } 203 | 204 | function extractFormat(raw: string | null) { 205 | if (!raw) { 206 | return undefined 207 | } 208 | const v = Format[raw] 209 | if (!v) { 210 | return undefined 211 | } 212 | return v 213 | } 214 | 215 | function scaleValue(u: Unit | undefined, v: number) { 216 | if (!u) return undefined 217 | switch (u.unit) { 218 | case 'px': 219 | return u.value 220 | case '%': 221 | return Math.round(u.value / 100 * v) 222 | default: 223 | return undefined 224 | } 225 | } 226 | 227 | function cacheKey(url: URL, opts: ImageOptions) { 228 | let parts = [{ k: "_v", v: "1" }] 229 | for (const k of Object.keys(opts)) { 230 | const v = opts[k] 231 | const d = defaultImageOptions[k] 232 | if (v && (!d || v.valueOf() != d.valueOf())) { 233 | parts.push({ k: paramUrlMap[k], v: v.valueOf() }) 234 | } 235 | } 236 | if (opts.watermark) { 237 | for (let k of Object.keys(opts.watermark)) { 238 | const v = opts.watermark[k] 239 | const d = defaultWatermarkOptions[k] 240 | k = paramUrlWatermarkMap[k] 241 | if (v && (!d || v.valueOf() != d.valueOf())) { 242 | parts.push({ k: k, v: v.valueOf() }) 243 | } 244 | } 245 | } 246 | parts = parts.sort() 247 | return url.pathname + 248 | ":" + parts.map((p) => p.k).join("|") + // keys in plain english 249 | ":" + crypto.subtle.digestSync("sha-1", parts.map((p) => p.v).join("|"), "hex") // values as sha-1 hash 250 | } 251 | 252 | export class Unit { 253 | value: number 254 | unit: string 255 | hash: string 256 | 257 | constructor(raw?: number | string | null) { 258 | this.value = 1 259 | this.unit = "auto" 260 | if (raw && typeof raw === "string") { 261 | const match = raw.match(/^(\d+(\.\d+)?)(%|px)?$/) 262 | if (match) { 263 | if (match[2]) { 264 | this.value = parseFloat(match[1] + match[2]) 265 | } else { 266 | this.value = parseInt(match[1]) 267 | } 268 | this.unit = match[3] || 'px' 269 | } else { 270 | throw new Error("Invalid Unit value, must start with a number and end with either px or %:" + JSON.stringify(raw)) 271 | } 272 | } else if (typeof raw === "number") { 273 | this.value = raw 274 | } 275 | this.hash = `${this.value}${this.unit}` 276 | } 277 | 278 | public valueOf() { 279 | return `${this.value}${this.unit}` 280 | } 281 | 282 | public static parser(raw?: number | string | null) { 283 | return new Unit(raw) 284 | } 285 | } 286 | 287 | interface paramParser { 288 | (raw: any): any 289 | } 290 | const urlParams = [ 291 | { param: 'w', key: "width", parser: Unit.parser }, 292 | { param: 'h', key: "height", parser: Unit.parser }, 293 | { param: "f", key: "format", parser: extractFormat }, 294 | ] 295 | const paramUrlMap: any = {} 296 | urlParams.forEach((p) => paramUrlMap[p.key] = p.param) 297 | 298 | const urlParamsWatermark = urlParams.map((p) => { 299 | return { param: "w_" + p.param, key: p.key, parser: p.parser } 300 | }).concat([ 301 | { param: "w_url", key: "url", parser: (raw) => raw }, // set manually for now 302 | { param: "w_bg", key: "background", parser: (raw) => raw }, 303 | { param: "w_pos", key: "position", parser: (raw) => raw }, 304 | { param: "w_pad", key: "padding", parser: Unit.parser } 305 | ]) 306 | const paramUrlWatermarkMap: any = {} 307 | urlParamsWatermark.forEach((p) => paramUrlWatermarkMap[p.key] = p.param) 308 | 309 | enum Format { 310 | png = "png", 311 | jpeg = "jpeg", 312 | jpg = "jpeg", 313 | webp = "webp" 314 | } 315 | 316 | interface ImageOptions { 317 | width: Unit, 318 | height: Unit, 319 | format?: string, 320 | watermark?: WatermarkOptions, 321 | [index: string]: any 322 | } 323 | 324 | interface WatermarkOptions { 325 | width: Unit, 326 | height: Unit, 327 | url: string 328 | position?: string 329 | background?: string, 330 | padding?: Unit 331 | [index: string]: any 332 | } 333 | 334 | 335 | const defaultUnit = new Unit() 336 | const defaultSizeOptions: ImageOptions = { 337 | width: defaultUnit, 338 | height: defaultUnit, 339 | equivalent: function (other: ImageOptions) { 340 | return this.width === other.width && 341 | this.height === other.height 342 | } 343 | } 344 | const defaultImageOptions: ImageOptions = { 345 | width: defaultSizeOptions.width, 346 | height: defaultSizeOptions.height, 347 | equivalent: function (other: ImageOptions) { 348 | return defaultSizeOptions.equivalent(other) && 349 | this.format === other.format 350 | 351 | } 352 | } 353 | 354 | const defaultWatermarkOptions: WatermarkOptions = { 355 | url: "", 356 | background: "rgba(0,0,0,0.0)", 357 | width: defaultUnit, 358 | height: defaultUnit, 359 | padding: defaultUnit 360 | } --------------------------------------------------------------------------------