Update jimp

This commit is contained in:
C85297 2026-02-03 11:43:20 +00:00
parent ef696b3347
commit 8a504e7d75
No known key found for this signature in database
27 changed files with 783 additions and 606 deletions

View File

@ -2,11 +2,13 @@
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const BundleAnalyzerPlugin =
require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const glob = require("glob");
const path = require("path");
const nodeFlags = "--experimental-modules --experimental-json-modules --experimental-specifier-resolution=node --no-warnings --no-deprecation";
const nodeFlags =
"--experimental-modules --experimental-json-modules --experimental-specifier-resolution=node --no-warnings --no-deprecation";
/**
* Grunt configuration for building the app in various formats.
@ -21,56 +23,98 @@ module.exports = function (grunt) {
grunt.file.preserveBOM = false;
// Tasks
grunt.registerTask("dev",
grunt.registerTask(
"dev",
"A persistent task which creates a development build whenever source files are modified.",
["clean:dev", "clean:config", "exec:generateConfig", "concurrent:dev"]);
["clean:dev", "clean:config", "exec:generateConfig", "concurrent:dev"],
);
grunt.registerTask("prod",
grunt.registerTask(
"prod",
"Creates a production-ready build. Use the --msg flag to add a compile message.",
[
"eslint", "clean:prod", "clean:config", "exec:generateConfig", "findModules", "webpack:web",
"copy:standalone", "zip:standalone", "clean:standalone", "exec:calcDownloadHash", "chmod"
]);
"eslint",
"clean:prod",
"clean:config",
"exec:generateConfig",
"findModules",
"webpack:web",
"copy:standalone",
"zip:standalone",
"clean:standalone",
"exec:calcDownloadHash",
"chmod",
],
);
grunt.registerTask("node",
grunt.registerTask(
"node",
"Compiles CyberChef into a single NodeJS module.",
[
"clean:node", "clean:config", "clean:nodeConfig", "exec:generateConfig", "exec:generateNodeIndex"
]);
"clean:node",
"clean:config",
"clean:nodeConfig",
"exec:generateConfig",
"exec:generateNodeIndex",
],
);
grunt.registerTask("configTests",
grunt.registerTask(
"configTests",
"A task which configures config files in preparation for tests to be run. Use `npm test` to run tests.",
[
"clean:config", "clean:nodeConfig", "exec:generateConfig", "exec:generateNodeIndex"
]);
"clean:config",
"clean:nodeConfig",
"exec:generateConfig",
"exec:generateNodeIndex",
],
);
grunt.registerTask("testui",
grunt.registerTask(
"testui",
"A task which runs all the UI tests in the tests directory. The prod task must already have been run.",
["connect:prod", "exec:browserTests"]);
["connect:prod", "exec:browserTests"],
);
grunt.registerTask("testnodeconsumer",
grunt.registerTask(
"testnodeconsumer",
"A task which checks whether consuming CJS and ESM apps work with the CyberChef build",
["exec:setupNodeConsumers", "exec:testCJSNodeConsumer", "exec:testESMNodeConsumer", "exec:teardownNodeConsumers"]);
[
"exec:setupNodeConsumers",
"exec:testCJSNodeConsumer",
"exec:testESMNodeConsumer",
"exec:teardownNodeConsumers",
],
);
grunt.registerTask("default",
"Lints the code base",
["eslint", "exec:repoSize"]);
grunt.registerTask("default", "Lints the code base", [
"eslint",
"exec:repoSize",
]);
grunt.registerTask("lint", "eslint");
grunt.registerTask("findModules",
grunt.registerTask(
"findModules",
"Finds all generated modules and updates the entry point list for Webpack",
function(arg1, arg2) {
function (arg1, arg2) {
const moduleEntryPoints = listEntryModules();
grunt.log.writeln(`Found ${Object.keys(moduleEntryPoints).length} modules.`);
grunt.config.set("webpack.web.entry",
Object.assign({
main: "./src/web/index.js"
}, moduleEntryPoints));
});
grunt.log.writeln(
`Found ${Object.keys(moduleEntryPoints).length} modules.`,
);
grunt.config.set(
"webpack.web.entry",
Object.assign(
{
main: "./src/web/index.js",
},
moduleEntryPoints,
),
);
},
);
// Load tasks provided by each plugin
grunt.loadNpmTasks("grunt-eslint");
@ -84,7 +128,6 @@ module.exports = function (grunt) {
grunt.loadNpmTasks("grunt-contrib-connect");
grunt.loadNpmTasks("grunt-zip");
// Project configuration
const compileYear = grunt.template.today("UTC:yyyy"),
compileTime = grunt.template.today("UTC:dd/mm/yyyy HH:MM:ss") + " UTC",
@ -93,7 +136,9 @@ module.exports = function (grunt) {
BUILD_CONSTANTS = {
COMPILE_YEAR: JSON.stringify(compileYear),
COMPILE_TIME: JSON.stringify(compileTime),
COMPILE_MSG: JSON.stringify(grunt.option("compile-msg") || grunt.option("msg") || ""),
COMPILE_MSG: JSON.stringify(
grunt.option("compile-msg") || grunt.option("msg") || "",
),
PKG_VERSION: JSON.stringify(pkg.version),
},
moduleEntryPoints = listEntryModules(),
@ -106,20 +151,26 @@ module.exports = function (grunt) {
return {
mode: "production",
target: "web",
entry: Object.assign({
main: "./src/web/index.js"
}, moduleEntryPoints),
entry: Object.assign(
{
main: "./src/web/index.js",
},
moduleEntryPoints,
),
output: {
path: __dirname + "/build/prod",
filename: chunkData => {
return chunkData.chunk.name === "main" ? "assets/[name].js": "[name].js";
filename: (chunkData) => {
return chunkData.chunk.name === "main"
? "assets/[name].js"
: "[name].js";
},
globalObject: "this"
globalObject: "this",
},
resolve: {
alias: {
"./config/modules/OpModules.mjs": "./config/modules/Default.mjs"
}
"./config/modules/OpModules.mjs":
"./config/modules/Default.mjs",
},
},
plugins: [
new webpack.DefinePlugin(BUILD_CONSTANTS),
@ -134,29 +185,29 @@ module.exports = function (grunt) {
removeComments: true,
collapseWhitespace: true,
minifyJS: true,
minifyCSS: true
}
minifyCSS: true,
},
}),
new BundleAnalyzerPlugin({
analyzerMode: "static",
reportFilename: "BundleAnalyzerReport.html",
openAnalyzer: false
openAnalyzer: false,
}),
]
],
};
};
/**
* Generates an entry list for all the modules.
*/
function listEntryModules() {
const entryModules = {};
glob.sync("./src/core/config/modules/*.mjs").forEach(file => {
glob.sync("./src/core/config/modules/*.mjs").forEach((file) => {
const basename = path.basename(file);
if (basename !== "Default.mjs" && basename !== "OpModules.mjs")
entryModules["modules/" + basename.split(".mjs")[0]] = path.resolve(file);
entryModules["modules/" + basename.split(".mjs")[0]] =
path.resolve(file);
});
return entryModules;
@ -174,12 +225,14 @@ module.exports = function (grunt) {
if (!win) {
return cmds.join(";");
}
return cmds
// && means that subsequent commands will not be executed if the
// previous one fails. & would coninue on a fail
.join("&&")
// Windows does not support \n properly
.replace(/\n/g, "\\n");
return (
cmds
// && means that subsequent commands will not be executed if the
// previous one fails. & would coninue on a fail
.join("&&")
// Windows does not support \n properly
.replace(/\n/g, "\\n")
);
}
grunt.initConfig({
@ -187,13 +240,24 @@ module.exports = function (grunt) {
dev: ["build/dev/*"],
prod: ["build/prod/*"],
node: ["build/node/*"],
config: ["src/core/config/OperationConfig.json", "src/core/config/modules/*", "src/code/operations/index.mjs"],
nodeConfig: ["src/node/index.mjs", "src/node/config/OperationConfig.json"],
standalone: ["build/prod/CyberChef*.html"]
config: [
"src/core/config/OperationConfig.json",
"src/core/config/modules/*",
"src/code/operations/index.mjs",
],
nodeConfig: [
"src/node/index.mjs",
"src/node/config/OperationConfig.json",
],
standalone: ["build/prod/CyberChef*.html"],
},
eslint: {
configs: ["*.{js,mjs}"],
core: ["src/core/**/*.{js,mjs}", "!src/core/vendor/**/*", "!src/core/operations/legacy/**/*"],
core: [
"src/core/**/*.{js,mjs}",
"!src/core/vendor/**/*",
"!src/core/operations/legacy/**/*",
],
web: ["src/web/**/*.{js,mjs}", "!src/web/static/**/*"],
node: ["src/node/**/*.{js,mjs}"],
tests: ["tests/**/*.{js,mjs}"],
@ -208,21 +272,25 @@ module.exports = function (grunt) {
start: {
mode: "development",
target: "web",
entry: Object.assign({
main: "./src/web/index.js"
}, moduleEntryPoints),
entry: Object.assign(
{
main: "./src/web/index.js",
},
moduleEntryPoints,
),
resolve: {
alias: {
"./config/modules/OpModules.mjs": "./config/modules/Default.mjs"
}
"./config/modules/OpModules.mjs":
"./config/modules/Default.mjs",
},
},
devServer: {
port: grunt.option("port") || 8080,
client: {
logging: "error",
overlay: true
overlay: true,
},
hot: "only"
hot: "only",
},
plugins: [
new webpack.DefinePlugin(BUILD_CONSTANTS),
@ -233,9 +301,9 @@ module.exports = function (grunt) {
compileYear: compileYear,
compileTime: compileTime,
version: pkg.version,
})
]
}
}),
],
},
},
zip: {
standalone: {
@ -245,16 +313,16 @@ module.exports = function (grunt) {
"!build/prod/index.html",
"!build/prod/BundleAnalyzerReport.html",
],
dest: `build/prod/CyberChef_v${pkg.version}.zip`
}
dest: `build/prod/CyberChef_v${pkg.version}.zip`,
},
},
connect: {
prod: {
options: {
port: grunt.option("port") || 8000,
base: "build/prod/"
}
}
base: "build/prod/",
},
},
},
copy: {
ghPages: {
@ -262,70 +330,86 @@ module.exports = function (grunt) {
process: function (content, srcpath) {
if (srcpath.indexOf("index.html") >= 0) {
// Add Google Analytics code to index.html
content = content.replace("</body></html>",
grunt.file.read("src/web/static/ga.html") + "</body></html>");
content = content.replace(
"</body></html>",
grunt.file.read("src/web/static/ga.html") +
"</body></html>",
);
// Add Structured Data for SEO
content = content.replace("</head>",
content = content.replace(
"</head>",
"<script type='application/ld+json'>" +
JSON.stringify(JSON.parse(grunt.file.read("src/web/static/structuredData.json"))) +
"</script></head>");
JSON.stringify(
JSON.parse(
grunt.file.read(
"src/web/static/structuredData.json",
),
),
) +
"</script></head>",
);
return grunt.template.process(content, srcpath);
} else {
return content;
}
},
noProcess: ["**", "!**/*.html"]
noProcess: ["**", "!**/*.html"],
},
files: [
{
src: ["build/prod/index.html"],
dest: "build/prod/index.html"
}
]
dest: "build/prod/index.html",
},
],
},
standalone: {
options: {
process: function (content, srcpath) {
if (srcpath.indexOf("index.html") >= 0) {
// Replace download link with version number
content = content.replace(/<a [^>]+>Download CyberChef.+?<\/a>/,
`<span>Version ${pkg.version}</span>`);
content = content.replace(
/<a [^>]+>Download CyberChef.+?<\/a>/,
`<span>Version ${pkg.version}</span>`,
);
return grunt.template.process(content, srcpath);
} else {
return content;
}
},
noProcess: ["**", "!**/*.html"]
noProcess: ["**", "!**/*.html"],
},
files: [
{
src: ["build/prod/index.html"],
dest: `build/prod/CyberChef_v${pkg.version}.html`
}
]
}
dest: `build/prod/CyberChef_v${pkg.version}.html`,
},
],
},
},
chmod: {
build: {
options: {
mode: "755",
},
src: ["build/**/*", "build/"]
}
src: ["build/**/*", "build/"],
},
},
watch: {
config: {
files: ["src/core/operations/**/*", "!src/core/operations/index.mjs"],
tasks: ["exec:generateNodeIndex", "exec:generateConfig"]
}
files: [
"src/core/operations/**/*",
"!src/core/operations/index.mjs",
],
tasks: ["exec:generateNodeIndex", "exec:generateConfig"],
},
},
concurrent: {
dev: ["watch:config", "webpack-dev-server:start"],
options: {
logConcurrentOutput: true
}
logConcurrentOutput: true,
},
},
exec: {
calcDownloadHash: {
@ -334,12 +418,12 @@ module.exports = function (grunt) {
case "darwin":
return chainCommands([
`shasum -a 256 build/prod/CyberChef_v${pkg.version}.zip | awk '{print $1;}' > build/prod/sha256digest.txt`,
`sed -i '' -e "s/DOWNLOAD_HASH_PLACEHOLDER/$(cat build/prod/sha256digest.txt)/" build/prod/index.html`
`sed -i '' -e "s/DOWNLOAD_HASH_PLACEHOLDER/$(cat build/prod/sha256digest.txt)/" build/prod/index.html`,
]);
default:
return chainCommands([
`sha256sum build/prod/CyberChef_v${pkg.version}.zip | awk '{print $1;}' > build/prod/sha256digest.txt`,
`sed -i -e "s/DOWNLOAD_HASH_PLACEHOLDER/$(cat build/prod/sha256digest.txt)/" build/prod/index.html`
`sed -i -e "s/DOWNLOAD_HASH_PLACEHOLDER/$(cat build/prod/sha256digest.txt)/" build/prod/index.html`,
]);
}
},
@ -347,16 +431,16 @@ module.exports = function (grunt) {
repoSize: {
command: chainCommands([
"git ls-files | wc -l | xargs printf '\n%b\ttracked files\n'",
"du -hs | egrep -o '^[^\t]*' | xargs printf '%b\trepository size\n'"
"du -hs | egrep -o '^[^\t]*' | xargs printf '%b\trepository size\n'",
]),
stderr: false
stderr: false,
},
cleanGit: {
command: "git gc --prune=now --aggressive"
command: "git gc --prune=now --aggressive",
},
sitemap: {
command: `node ${nodeFlags} src/web/static/sitemap.mjs > build/prod/sitemap.xml`,
sync: true
sync: true,
},
generateConfig: {
command: chainCommands([
@ -364,20 +448,20 @@ module.exports = function (grunt) {
"echo [] > src/core/config/OperationConfig.json",
`node ${nodeFlags} src/core/config/scripts/generateOpsIndex.mjs`,
`node ${nodeFlags} src/core/config/scripts/generateConfig.mjs`,
"echo '--- Config scripts finished. ---\n'"
"echo '--- Config scripts finished. ---\n'",
]),
sync: true
sync: true,
},
generateNodeIndex: {
command: chainCommands([
"echo '\n--- Regenerating node index ---'",
`node ${nodeFlags} src/node/config/scripts/generateNodeIndex.mjs`,
"echo '--- Node index generated. ---\n'"
"echo '--- Node index generated. ---\n'",
]),
sync: true
sync: true,
},
browserTests: {
command: "./node_modules/.bin/nightwatch --env prod"
command: "./node_modules/.bin/nightwatch --env prod",
},
setupNodeConsumers: {
command: chainCommands([
@ -386,14 +470,14 @@ module.exports = function (grunt) {
`mkdir ${nodeConsumerTestPath}`,
`cp tests/node/consumers/* ${nodeConsumerTestPath}`,
`cd ${nodeConsumerTestPath}`,
"npm link cyberchef"
"npm link cyberchef",
]),
sync: true
sync: true,
},
teardownNodeConsumers: {
command: chainCommands([
`rm -rf ${nodeConsumerTestPath}`,
"echo '\n--- Node consumer tests complete ---'"
"echo '\n--- Node consumer tests complete ---'",
]),
},
testCJSNodeConsumer: {
@ -419,7 +503,7 @@ module.exports = function (grunt) {
return `find ./node_modules/crypto-api/src/ \\( -type d -name .git -prune \\) -o -type f -print0 | xargs -0 sed -i -e '/\\.mjs/!s/\\(from "\\.[^"]*\\)";/\\1.mjs";/g'`;
}
},
stdout: false
stdout: false,
},
fixSnackbarMarkup: {
command: function () {
@ -430,20 +514,8 @@ module.exports = function (grunt) {
return `sed -i 's/<div id=snackbar-container\\/>/<div id=snackbar-container>/g' ./node_modules/snackbarjs/src/snackbar.js`;
}
},
stdout: false
stdout: false,
},
fixJimpModule: {
command: function () {
switch (process.platform) {
case "darwin":
// Space added before comma to prevent multiple modifications
return `sed -i '' 's/"es\\/index.js",/"es\\/index.js" ,\\n "type": "module",/' ./node_modules/jimp/package.json`;
default:
return `sed -i 's/"es\\/index.js",/"es\\/index.js" ,\\n "type": "module",/' ./node_modules/jimp/package.json`;
}
},
stdout: false
}
},
});
};

View File

@ -200,7 +200,7 @@
"testuidev": "npx nightwatch --env=dev",
"lint": "npx grunt lint",
"lint:grammar": "cspell ./src",
"postinstall": "npx grunt exec:fixCryptoApiImports && npx grunt exec:fixSnackbarMarkup && npx grunt exec:fixJimpModule",
"postinstall": "npx grunt exec:fixCryptoApiImports && npx grunt exec:fixSnackbarMarkup",
"newop": "node --experimental-modules --experimental-json-modules src/core/config/scripts/newOperation.mjs",
"minor": "node --experimental-modules --experimental-json-modules src/core/config/scripts/newMinorVersion.mjs",
"getheapsize": "node -e 'console.log(`node heap limit = ${require(\"v8\").getHeapStatistics().heap_size_limit / (1024 * 1024)} Mb`)'",

View File

@ -10,7 +10,7 @@ import OperationError from "../errors/OperationError.mjs";
import jsQR from "jsqr";
import qr from "qr-image";
import Utils from "../Utils.mjs";
import Jimp from "jimp/es/index.js";
import { Jimp, JimpMime } from "jimp";
/**
* Parses a QR code image from an image
@ -29,18 +29,31 @@ export async function parseQrCode(input, normalise) {
try {
if (normalise) {
image.rgba(false);
image.background(0xFFFFFFFF);
image.normalize();
image.greyscale();
image = await image.getBufferAsync(Jimp.MIME_JPEG);
image = await Jimp.read(image);
image.normalize();
}
} catch (err) {
throw new OperationError(`Error normalising image. (${err})`);
}
const qrData = jsQR(image.bitmap.data, image.getWidth(), image.getHeight());
// Remove transparency which jsQR cannot handle
image.scan((x, y, idx) => {
// If pixel is fully transparent, make it opaque white
if (image.bitmap.data[idx + 3] === 0x00) {
image.bitmap.data[idx + 0] = 0xff;
image.bitmap.data[idx + 1] = 0xff;
image.bitmap.data[idx + 2] = 0xff;
}
// Otherwise, make it fully opaque at its existing colour
image.bitmap.data[idx + 3] = 0xff;
});
image = await Jimp.read(await image.getBuffer(JimpMime.jpeg));
const qrData = jsQR(
new Uint8ClampedArray(image.bitmap.data),
image.width,
image.height,
);
if (qrData) {
return qrData.data;
} else {
@ -58,7 +71,13 @@ export async function parseQrCode(input, normalise) {
* @param {string} errorCorrection
* @returns {ArrayBuffer}
*/
export function generateQrCode(input, format, moduleSize, margin, errorCorrection) {
export function generateQrCode(
input,
format,
moduleSize,
margin,
errorCorrection,
) {
const formats = ["SVG", "EPS", "PDF", "PNG"];
if (!formats.includes(format.toUpperCase())) {
throw new OperationError("Unsupported QR code format.");
@ -70,7 +89,7 @@ export function generateQrCode(input, format, moduleSize, margin, errorCorrectio
type: format,
size: moduleSize,
margin: margin,
"ec_level": errorCorrection.charAt(0).toUpperCase()
ec_level: errorCorrection.charAt(0).toUpperCase(),
});
} catch (err) {
throw new OperationError(`Error generating QR code. (${err})`);

View File

@ -9,13 +9,19 @@ import OperationError from "../errors/OperationError.mjs";
import { isImage } from "../lib/FileType.mjs";
import { toBase64 } from "../lib/Base64.mjs";
import { isWorkerEnvironment } from "../Utils.mjs";
import Jimp from "jimp/es/index.js";
import {
Jimp,
JimpMime,
ResizeStrategy,
measureText,
measureTextHeight,
loadFont,
} from "jimp";
/**
* Add Text To Image operation
*/
class AddTextToImage extends Operation {
/**
* AddTextToImage constructor
*/
@ -24,7 +30,8 @@ class AddTextToImage extends Operation {
this.name = "Add Text To Image";
this.module = "Image";
this.description = "Adds text onto an image.<br><br>Text can be horizontally or vertically aligned, or the position can be manually specified.<br>Variants of the Roboto font face are available in any size or colour.";
this.description =
"Adds text onto an image.<br><br>Text can be horizontally or vertically aligned, or the position can be manually specified.<br>Variants of the Roboto font face are available in any size or colour.";
this.infoURL = "";
this.inputType = "ArrayBuffer";
this.outputType = "ArrayBuffer";
@ -33,72 +40,67 @@ class AddTextToImage extends Operation {
{
name: "Text",
type: "string",
value: ""
value: "",
},
{
name: "Horizontal align",
type: "option",
value: ["None", "Left", "Center", "Right"]
value: ["None", "Left", "Center", "Right"],
},
{
name: "Vertical align",
type: "option",
value: ["None", "Top", "Middle", "Bottom"]
value: ["None", "Top", "Middle", "Bottom"],
},
{
name: "X position",
type: "number",
value: 0
value: 0,
},
{
name: "Y position",
type: "number",
value: 0
value: 0,
},
{
name: "Size",
type: "number",
value: 32,
min: 8
min: 8,
},
{
name: "Font face",
type: "option",
value: [
"Roboto",
"Roboto Black",
"Roboto Mono",
"Roboto Slab"
]
value: ["Roboto", "Roboto Black", "Roboto Mono", "Roboto Slab"],
},
{
name: "Red",
type: "number",
value: 255,
min: 0,
max: 255
max: 255,
},
{
name: "Green",
type: "number",
value: 255,
min: 0,
max: 255
max: 255,
},
{
name: "Blue",
type: "number",
value: 255,
min: 0,
max: 255
max: 255,
},
{
name: "Alpha",
type: "number",
value: 255,
min: 0,
max: 255
}
max: 255,
},
];
}
@ -137,35 +139,49 @@ class AddTextToImage extends Operation {
const fontsMap = {};
const fonts = [
import(/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/Roboto72White.fnt"),
import(/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/RobotoBlack72White.fnt"),
import(/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/RobotoMono72White.fnt"),
import(/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/RobotoSlab72White.fnt")
import(
/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/Roboto72White.fnt"
),
import(
/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/RobotoBlack72White.fnt"
),
import(
/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/RobotoMono72White.fnt"
),
import(
/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/RobotoSlab72White.fnt"
),
];
await Promise.all(fonts)
.then(fonts => {
fontsMap.Roboto = fonts[0];
fontsMap["Roboto Black"] = fonts[1];
fontsMap["Roboto Mono"] = fonts[2];
fontsMap["Roboto Slab"] = fonts[3];
});
await Promise.all(fonts).then((fonts) => {
fontsMap.Roboto = fonts[0];
fontsMap["Roboto Black"] = fonts[1];
fontsMap["Roboto Mono"] = fonts[2];
fontsMap["Roboto Slab"] = fonts[3];
});
// Make Webpack load the png font images
await Promise.all([
import(/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/Roboto72White.png"),
import(/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/RobotoSlab72White.png"),
import(/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/RobotoMono72White.png"),
import(/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/RobotoBlack72White.png")
import(
/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/Roboto72White.png"
),
import(
/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/RobotoSlab72White.png"
),
import(
/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/RobotoMono72White.png"
),
import(
/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/RobotoBlack72White.png"
),
]);
const font = fontsMap[fontFace];
// LoadFont needs an absolute url, so append the font name to self.docURL
const jimpFont = await Jimp.loadFont(self.docURL + "/" + font.default);
const jimpFont = await loadFont(self.docURL + "/" + font.default);
jimpFont.pages.forEach(function(page) {
jimpFont.pages.forEach(function (page) {
if (page.bitmap) {
// Adjust the RGB values of the image pages to change the font colour.
const pageWidth = page.bitmap.width;
@ -175,22 +191,31 @@ class AddTextToImage extends Operation {
const idx = (iy * pageWidth + ix) << 2;
const newRed = page.bitmap.data[idx] - (255 - red);
const newGreen = page.bitmap.data[idx + 1] - (255 - green);
const newBlue = page.bitmap.data[idx + 2] - (255 - blue);
const newAlpha = page.bitmap.data[idx + 3] - (255 - alpha);
const newGreen =
page.bitmap.data[idx + 1] - (255 - green);
const newBlue =
page.bitmap.data[idx + 2] - (255 - blue);
const newAlpha =
page.bitmap.data[idx + 3] - (255 - alpha);
// Make sure the bitmap values don't go below 0 as that makes jimp very unhappy
page.bitmap.data[idx] = (newRed > 0) ? newRed : 0;
page.bitmap.data[idx + 1] = (newGreen > 0) ? newGreen : 0;
page.bitmap.data[idx + 2] = (newBlue > 0) ? newBlue : 0;
page.bitmap.data[idx + 3] = (newAlpha > 0) ? newAlpha : 0;
page.bitmap.data[idx] = newRed > 0 ? newRed : 0;
page.bitmap.data[idx + 1] =
newGreen > 0 ? newGreen : 0;
page.bitmap.data[idx + 2] =
newBlue > 0 ? newBlue : 0;
page.bitmap.data[idx + 3] =
newAlpha > 0 ? newAlpha : 0;
}
}
}
});
// Create a temporary image to hold the rendered text
const textImage = new Jimp(Jimp.measureText(jimpFont, text), Jimp.measureTextHeight(jimpFont, text));
const textImage = new Jimp({
width: measureText(jimpFont, text),
height: measureTextHeight(jimpFont, text),
});
textImage.print(jimpFont, 0, 0, text);
// Scale the rendered text image to the correct size
@ -198,9 +223,9 @@ class AddTextToImage extends Operation {
if (size !== 1) {
// Use bicubic for decreasing size
if (size > 1) {
textImage.scale(scaleFactor, Jimp.RESIZE_BICUBIC);
textImage.scale(scaleFactor, ResizeStrategy.BICUBIC);
} else {
textImage.scale(scaleFactor, Jimp.RESIZE_BILINEAR);
textImage.scale(scaleFactor, ResizeStrategy.BILINEAR);
}
}
@ -210,10 +235,10 @@ class AddTextToImage extends Operation {
xPos = 0;
break;
case "Center":
xPos = (image.getWidth() / 2) - (textImage.getWidth() / 2);
xPos = image.width / 2 - textImage.width / 2;
break;
case "Right":
xPos = image.getWidth() - textImage.getWidth();
xPos = image.width - textImage.width;
break;
}
@ -222,10 +247,10 @@ class AddTextToImage extends Operation {
yPos = 0;
break;
case "Middle":
yPos = (image.getHeight() / 2) - (textImage.getHeight() / 2);
yPos = image.height / 2 - textImage.height / 2;
break;
case "Bottom":
yPos = image.getHeight() - textImage.getHeight();
yPos = image.height - textImage.height;
break;
}
@ -233,10 +258,10 @@ class AddTextToImage extends Operation {
image.blit(textImage, xPos, yPos);
let imageBuffer;
if (image.getMIME() === "image/gif") {
imageBuffer = await image.getBufferAsync(Jimp.MIME_PNG);
if (image.mime === "image/gif") {
imageBuffer = await image.getBuffer(JimpMime.png);
} else {
imageBuffer = await image.getBufferAsync(Jimp.AUTO);
imageBuffer = await image.getBuffer(image.mime);
}
return imageBuffer.buffer;
} catch (err) {
@ -261,7 +286,6 @@ class AddTextToImage extends Operation {
return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
}
}
export default AddTextToImage;

View File

@ -10,13 +10,12 @@ import { isWorkerEnvironment } from "../Utils.mjs";
import { isImage } from "../lib/FileType.mjs";
import { toBase64 } from "../lib/Base64.mjs";
import { gaussianBlur } from "../lib/ImageManipulation.mjs";
import Jimp from "jimp/es/index.js";
import { Jimp, JimpMime } from "jimp";
/**
* Blur Image operation
*/
class BlurImage extends Operation {
/**
* BlurImage constructor
*/
@ -25,7 +24,8 @@ class BlurImage extends Operation {
this.name = "Blur Image";
this.module = "Image";
this.description = "Applies a blur effect to the image.<br><br>Gaussian blur is much slower than fast blur, but produces better results.";
this.description =
"Applies a blur effect to the image.<br><br>Gaussian blur is much slower than fast blur, but produces better results.";
this.infoURL = "https://wikipedia.org/wiki/Gaussian_blur";
this.inputType = "ArrayBuffer";
this.outputType = "ArrayBuffer";
@ -35,13 +35,13 @@ class BlurImage extends Operation {
name: "Amount",
type: "number",
value: 5,
min: 1
min: 1,
},
{
name: "Type",
type: "option",
value: ["Fast", "Gaussian"]
}
value: ["Fast", "Gaussian"],
},
];
}
@ -78,10 +78,10 @@ class BlurImage extends Operation {
}
let imageBuffer;
if (image.getMIME() === "image/gif") {
imageBuffer = await image.getBufferAsync(Jimp.MIME_PNG);
if (image.mime === "image/gif") {
imageBuffer = await image.getBuffer(JimpMime.png);
} else {
imageBuffer = await image.getBufferAsync(Jimp.AUTO);
imageBuffer = await image.getBuffer(image.mime);
}
return imageBuffer.buffer;
} catch (err) {
@ -106,7 +106,6 @@ class BlurImage extends Operation {
return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
}
}
export default BlurImage;

View File

@ -9,13 +9,18 @@ import OperationError from "../errors/OperationError.mjs";
import { isImage } from "../lib/FileType.mjs";
import { toBase64 } from "../lib/Base64.mjs";
import { isWorkerEnvironment } from "../Utils.mjs";
import Jimp from "jimp/es/index.js";
import {
Jimp,
JimpMime,
ResizeStrategy,
HorizontalAlign,
VerticalAlign,
} from "jimp";
/**
* Contain Image operation
*/
class ContainImage extends Operation {
/**
* ContainImage constructor
*/
@ -24,7 +29,8 @@ class ContainImage extends Operation {
this.name = "Contain Image";
this.module = "Image";
this.description = "Scales an image to the specified width and height, maintaining the aspect ratio. The image may be letterboxed.";
this.description =
"Scales an image to the specified width and height, maintaining the aspect ratio. The image may be letterboxed.";
this.infoURL = "";
this.inputType = "ArrayBuffer";
this.outputType = "ArrayBuffer";
@ -34,33 +40,25 @@ class ContainImage extends Operation {
name: "Width",
type: "number",
value: 100,
min: 1
min: 1,
},
{
name: "Height",
type: "number",
value: 100,
min: 1
min: 1,
},
{
name: "Horizontal align",
type: "option",
value: [
"Left",
"Center",
"Right"
],
defaultIndex: 1
value: ["Left", "Center", "Right"],
defaultIndex: 1,
},
{
name: "Vertical align",
type: "option",
value: [
"Top",
"Middle",
"Bottom"
],
defaultIndex: 1
value: ["Top", "Middle", "Bottom"],
defaultIndex: 1,
},
{
name: "Resizing algorithm",
@ -70,15 +68,15 @@ class ContainImage extends Operation {
"Bilinear",
"Bicubic",
"Hermite",
"Bezier"
"Bezier",
],
defaultIndex: 1
defaultIndex: 1,
},
{
name: "Opaque background",
type: "boolean",
value: true
}
value: true,
},
];
}
@ -91,20 +89,20 @@ class ContainImage extends Operation {
const [width, height, hAlign, vAlign, alg, opaqueBg] = args;
const resizeMap = {
"Nearest Neighbour": Jimp.RESIZE_NEAREST_NEIGHBOR,
"Bilinear": Jimp.RESIZE_BILINEAR,
"Bicubic": Jimp.RESIZE_BICUBIC,
"Hermite": Jimp.RESIZE_HERMITE,
"Bezier": Jimp.RESIZE_BEZIER
"Nearest Neighbour": ResizeStrategy.NEAREST_NEIGHBOR,
Bilinear: ResizeStrategy.BILINEAR,
Bicubic: ResizeStrategy.BICUBIC,
Hermite: ResizeStrategy.HERMITE,
Bezier: ResizeStrategy.BEZIER,
};
const alignMap = {
"Left": Jimp.HORIZONTAL_ALIGN_LEFT,
"Center": Jimp.HORIZONTAL_ALIGN_CENTER,
"Right": Jimp.HORIZONTAL_ALIGN_RIGHT,
"Top": Jimp.VERTICAL_ALIGN_TOP,
"Middle": Jimp.VERTICAL_ALIGN_MIDDLE,
"Bottom": Jimp.VERTICAL_ALIGN_BOTTOM
Left: HorizontalAlign.LEFT,
Center: HorizontalAlign.CENTER,
Right: HorizontalAlign.RIGHT,
Top: VerticalAlign.TOP,
Middle: VerticalAlign.MIDDLE,
Bottom: VerticalAlign.BOTTOM,
};
if (!isImage(input)) {
@ -120,19 +118,24 @@ class ContainImage extends Operation {
try {
if (isWorkerEnvironment())
self.sendStatusMessage("Containing image...");
image.contain(width, height, alignMap[hAlign] | alignMap[vAlign], resizeMap[alg]);
image.contain(
width,
height,
alignMap[hAlign] | alignMap[vAlign],
resizeMap[alg],
);
if (opaqueBg) {
const newImage = await Jimp.read(width, height, 0x000000FF);
const newImage = await Jimp.read(width, height, 0x000000ff);
newImage.blit(image, 0, 0);
image = newImage;
}
let imageBuffer;
if (image.getMIME() === "image/gif") {
imageBuffer = await image.getBufferAsync(Jimp.MIME_PNG);
if (image.mime === "image/gif") {
imageBuffer = await image.getBuffer(JimpMime.png);
} else {
imageBuffer = await image.getBufferAsync(Jimp.AUTO);
imageBuffer = await image.getBuffer(image.mime);
}
return imageBuffer.buffer;
} catch (err) {
@ -156,7 +159,6 @@ class ContainImage extends Operation {
return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
}
}
export default ContainImage;

View File

@ -8,13 +8,12 @@ import Operation from "../Operation.mjs";
import OperationError from "../errors/OperationError.mjs";
import { isImage } from "../lib/FileType.mjs";
import { toBase64 } from "../lib/Base64.mjs";
import Jimp from "jimp/es/index.js";
import { Jimp, JimpMime, PNGFilterType } from "jimp";
/**
* Convert Image Format operation
*/
class ConvertImageFormat extends Operation {
/**
* ConvertImageFormat constructor
*/
@ -23,7 +22,8 @@ class ConvertImageFormat extends Operation {
this.name = "Convert Image Format";
this.module = "Image";
this.description = "Converts an image between different formats. Supported formats:<br><ul><li>Joint Photographic Experts Group (JPEG)</li><li>Portable Network Graphics (PNG)</li><li>Bitmap (BMP)</li><li>Tagged Image File Format (TIFF)</li></ul><br>Note: GIF files are supported for input, but cannot be outputted.";
this.description =
"Converts an image between different formats. Supported formats:<br><ul><li>Joint Photographic Experts Group (JPEG)</li><li>Portable Network Graphics (PNG)</li><li>Bitmap (BMP)</li><li>Tagged Image File Format (TIFF)</li></ul><br>Note: GIF files are supported for input, but cannot be outputted.";
this.infoURL = "https://wikipedia.org/wiki/Image_file_formats";
this.inputType = "ArrayBuffer";
this.outputType = "ArrayBuffer";
@ -32,39 +32,27 @@ class ConvertImageFormat extends Operation {
{
name: "Output Format",
type: "option",
value: [
"JPEG",
"PNG",
"BMP",
"TIFF"
]
value: ["JPEG", "PNG", "BMP", "TIFF"],
},
{
name: "JPEG Quality",
type: "number",
value: 80,
min: 1,
max: 100
max: 100,
},
{
name: "PNG Filter Type",
type: "option",
value: [
"Auto",
"None",
"Sub",
"Up",
"Average",
"Paeth"
]
value: ["Auto", "None", "Sub", "Up", "Average", "Paeth"],
},
{
name: "PNG Deflate Level",
type: "number",
value: 9,
min: 0,
max: 9
}
max: 9,
},
];
}
@ -76,19 +64,19 @@ class ConvertImageFormat extends Operation {
async run(input, args) {
const [format, jpegQuality, pngFilterType, pngDeflateLevel] = args;
const formatMap = {
"JPEG": Jimp.MIME_JPEG,
"PNG": Jimp.MIME_PNG,
"BMP": Jimp.MIME_BMP,
"TIFF": Jimp.MIME_TIFF
JPEG: JimpMime.jpeg,
PNG: JimpMime.png,
BMP: JimpMime.bmp,
TIFF: JimpMime.tiff,
};
const pngFilterMap = {
"Auto": Jimp.PNG_FILTER_AUTO,
"None": Jimp.PNG_FILTER_NONE,
"Sub": Jimp.PNG_FILTER_SUB,
"Up": Jimp.PNG_FILTER_UP,
"Average": Jimp.PNG_FILTER_AVERAGE,
"Paeth": Jimp.PNG_FILTER_PATH
Auto: PNGFilterType.AUTO,
None: PNGFilterType.NONE,
Sub: PNGFilterType.SUB,
Up: PNGFilterType.UP,
Average: PNGFilterType.AVERAGE,
Paeth: PNGFilterType.PATH,
};
const mime = formatMap[format];
@ -113,7 +101,7 @@ class ConvertImageFormat extends Operation {
break;
}
const imageBuffer = await image.getBufferAsync(mime);
const imageBuffer = await image.getBuffer(mime);
return imageBuffer.buffer;
} catch (err) {
throw new OperationError(`Error converting image format. (${err})`);
@ -137,7 +125,6 @@ class ConvertImageFormat extends Operation {
return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
}
}
export default ConvertImageFormat;

View File

@ -9,13 +9,18 @@ import OperationError from "../errors/OperationError.mjs";
import { isImage } from "../lib/FileType.mjs";
import { toBase64 } from "../lib/Base64.mjs";
import { isWorkerEnvironment } from "../Utils.mjs";
import jimp from "jimp/es/index.js";
import {
Jimp,
JimpMime,
ResizeStrategy,
HorizontalAlign,
VerticalAlign,
} from "jimp";
/**
* Cover Image operation
*/
class CoverImage extends Operation {
/**
* CoverImage constructor
*/
@ -24,7 +29,8 @@ class CoverImage extends Operation {
this.name = "Cover Image";
this.module = "Image";
this.description = "Scales the image to the given width and height, keeping the aspect ratio. The image may be clipped.";
this.description =
"Scales the image to the given width and height, keeping the aspect ratio. The image may be clipped.";
this.infoURL = "";
this.inputType = "ArrayBuffer";
this.outputType = "ArrayBuffer";
@ -34,33 +40,25 @@ class CoverImage extends Operation {
name: "Width",
type: "number",
value: 100,
min: 1
min: 1,
},
{
name: "Height",
type: "number",
value: 100,
min: 1
min: 1,
},
{
name: "Horizontal align",
type: "option",
value: [
"Left",
"Center",
"Right"
],
defaultIndex: 1
value: ["Left", "Center", "Right"],
defaultIndex: 1,
},
{
name: "Vertical align",
type: "option",
value: [
"Top",
"Middle",
"Bottom"
],
defaultIndex: 1
value: ["Top", "Middle", "Bottom"],
defaultIndex: 1,
},
{
name: "Resizing algorithm",
@ -70,10 +68,10 @@ class CoverImage extends Operation {
"Bilinear",
"Bicubic",
"Hermite",
"Bezier"
"Bezier",
],
defaultIndex: 1
}
defaultIndex: 1,
},
];
}
@ -86,20 +84,20 @@ class CoverImage extends Operation {
const [width, height, hAlign, vAlign, alg] = args;
const resizeMap = {
"Nearest Neighbour": jimp.RESIZE_NEAREST_NEIGHBOR,
"Bilinear": jimp.RESIZE_BILINEAR,
"Bicubic": jimp.RESIZE_BICUBIC,
"Hermite": jimp.RESIZE_HERMITE,
"Bezier": jimp.RESIZE_BEZIER
"Nearest Neighbour": ResizeStrategy.NEAREST_NEIGHBOR,
Bilinear: ResizeStrategy.BILINEAR,
Bicubic: ResizeStrategy.BICUBIC,
Hermite: ResizeStrategy.HERMITE,
Bezier: ResizeStrategy.BEZIER,
};
const alignMap = {
"Left": jimp.HORIZONTAL_ALIGN_LEFT,
"Center": jimp.HORIZONTAL_ALIGN_CENTER,
"Right": jimp.HORIZONTAL_ALIGN_RIGHT,
"Top": jimp.VERTICAL_ALIGN_TOP,
"Middle": jimp.VERTICAL_ALIGN_MIDDLE,
"Bottom": jimp.VERTICAL_ALIGN_BOTTOM
Left: HorizontalAlign.LEFT,
Center: HorizontalAlign.CENTER,
Right: HorizontalAlign.RIGHT,
Top: VerticalAlign.TOP,
Middle: VerticalAlign.MIDDLE,
Bottom: VerticalAlign.BOTTOM,
};
if (!isImage(input)) {
@ -108,19 +106,24 @@ class CoverImage extends Operation {
let image;
try {
image = await jimp.read(input);
image = await Jimp.read(input);
} catch (err) {
throw new OperationError(`Error loading image. (${err})`);
}
try {
if (isWorkerEnvironment())
self.sendStatusMessage("Covering image...");
image.cover(width, height, alignMap[hAlign] | alignMap[vAlign], resizeMap[alg]);
image.cover(
width,
height,
alignMap[hAlign] | alignMap[vAlign],
resizeMap[alg],
);
let imageBuffer;
if (image.getMIME() === "image/gif") {
imageBuffer = await image.getBufferAsync(jimp.MIME_PNG);
if (image.mime === "image/gif") {
imageBuffer = await image.getBuffer(JimpMime.png);
} else {
imageBuffer = await image.getBufferAsync(jimp.AUTO);
imageBuffer = await image.getBuffer(image.mime);
}
return imageBuffer.buffer;
} catch (err) {
@ -144,7 +147,6 @@ class CoverImage extends Operation {
return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
}
}
export default CoverImage;

View File

@ -9,13 +9,12 @@ import OperationError from "../errors/OperationError.mjs";
import { isImage } from "../lib/FileType.mjs";
import { toBase64 } from "../lib/Base64.mjs";
import { isWorkerEnvironment } from "../Utils.mjs";
import Jimp from "jimp/es/index.js";
import { Jimp, JimpMime } from "jimp";
/**
* Crop Image operation
*/
class CropImage extends Operation {
/**
* CropImage constructor
*/
@ -24,7 +23,8 @@ class CropImage extends Operation {
this.name = "Crop Image";
this.module = "Image";
this.description = "Crops an image to the specified region, or automatically crops edges.<br><br><b><u>Autocrop</u></b><br>Automatically crops same-colour borders from the image.<br><br><u>Autocrop tolerance</u><br>A percentage value for the tolerance of colour difference between pixels.<br><br><u>Only autocrop frames</u><br>Only crop real frames (all sides must have the same border)<br><br><u>Symmetric autocrop</u><br>Force autocrop to be symmetric (top/bottom and left/right are cropped by the same amount)<br><br><u>Autocrop keep border</u><br>The number of pixels of border to leave around the image.";
this.description =
"Crops an image to the specified region, or automatically crops edges.<br><br><b><u>Autocrop</u></b><br>Automatically crops same-colour borders from the image.<br><br><u>Autocrop tolerance</u><br>A percentage value for the tolerance of colour difference between pixels.<br><br><u>Only autocrop frames</u><br>Only crop real frames (all sides must have the same border)<br><br><u>Symmetric autocrop</u><br>Force autocrop to be symmetric (top/bottom and left/right are cropped by the same amount)<br><br><u>Autocrop keep border</u><br>The number of pixels of border to leave around the image.";
this.infoURL = "https://wikipedia.org/wiki/Cropping_(image)";
this.inputType = "ArrayBuffer";
this.outputType = "ArrayBuffer";
@ -34,30 +34,30 @@ class CropImage extends Operation {
name: "X Position",
type: "number",
value: 0,
min: 0
min: 0,
},
{
name: "Y Position",
type: "number",
value: 0,
min: 0
min: 0,
},
{
name: "Width",
type: "number",
value: 10,
min: 1
min: 1,
},
{
name: "Height",
type: "number",
value: 10,
min: 1
min: 1,
},
{
name: "Autocrop",
type: "boolean",
value: false
value: false,
},
{
name: "Autocrop tolerance (%)",
@ -65,24 +65,24 @@ class CropImage extends Operation {
value: 0.02,
min: 0,
max: 100,
step: 0.01
step: 0.01,
},
{
name: "Only autocrop frames",
type: "boolean",
value: true
value: true,
},
{
name: "Symmetric autocrop",
type: "boolean",
value: false
value: false,
},
{
name: "Autocrop keep border (px)",
type: "number",
value: 0,
min: 0
}
min: 0,
},
];
}
@ -92,7 +92,17 @@ class CropImage extends Operation {
* @returns {byteArray}
*/
async run(input, args) {
const [xPos, yPos, width, height, autocrop, autoTolerance, autoFrames, autoSymmetric, autoBorder] = args;
const [
xPos,
yPos,
width,
height,
autocrop,
autoTolerance,
autoFrames,
autoSymmetric,
autoBorder,
] = args;
if (!isImage(input)) {
throw new OperationError("Invalid file type.");
}
@ -108,20 +118,20 @@ class CropImage extends Operation {
self.sendStatusMessage("Cropping image...");
if (autocrop) {
image.autocrop({
tolerance: (autoTolerance / 100),
tolerance: autoTolerance / 100,
cropOnlyFrames: autoFrames,
cropSymmetric: autoSymmetric,
leaveBorder: autoBorder
leaveBorder: autoBorder,
});
} else {
image.crop(xPos, yPos, width, height);
}
let imageBuffer;
if (image.getMIME() === "image/gif") {
imageBuffer = await image.getBufferAsync(Jimp.MIME_PNG);
if (image.mime === "image/gif") {
imageBuffer = await image.getBuffer(JimpMime.png);
} else {
imageBuffer = await image.getBufferAsync(Jimp.AUTO);
imageBuffer = await image.getBuffer(image.mime);
}
return imageBuffer.buffer;
} catch (err) {
@ -145,7 +155,6 @@ class CropImage extends Operation {
return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
}
}
export default CropImage;

View File

@ -9,13 +9,12 @@ import OperationError from "../errors/OperationError.mjs";
import { isImage } from "../lib/FileType.mjs";
import { toBase64 } from "../lib/Base64.mjs";
import { isWorkerEnvironment } from "../Utils.mjs";
import Jimp from "jimp/es/index.js";
import { Jimp, JimpMime } from "jimp";
/**
* Image Dither operation
*/
class DitherImage extends Operation {
/**
* DitherImage constructor
*/
@ -54,14 +53,16 @@ class DitherImage extends Operation {
image.dither565();
let imageBuffer;
if (image.getMIME() === "image/gif") {
imageBuffer = await image.getBufferAsync(Jimp.MIME_PNG);
if (image.mime === "image/gif") {
imageBuffer = await image.getBuffer(JimpMime.png);
} else {
imageBuffer = await image.getBufferAsync(Jimp.AUTO);
imageBuffer = await image.getBuffer(image.mime);
}
return imageBuffer.buffer;
} catch (err) {
throw new OperationError(`Error applying dither to image. (${err})`);
throw new OperationError(
`Error applying dither to image. (${err})`,
);
}
}
@ -81,7 +82,6 @@ class DitherImage extends Operation {
return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
}
}
export default DitherImage;

View File

@ -9,13 +9,12 @@ import OperationError from "../errors/OperationError.mjs";
import Utils from "../Utils.mjs";
import { fromBinary } from "../lib/Binary.mjs";
import { isImage } from "../lib/FileType.mjs";
import Jimp from "jimp/es/index.js";
import { Jimp } from "jimp";
/**
* Extract LSB operation
*/
class ExtractLSB extends Operation {
/**
* ExtractLSB constructor
*/
@ -24,8 +23,10 @@ class ExtractLSB extends Operation {
this.name = "Extract LSB";
this.module = "Image";
this.description = "Extracts the Least Significant Bit data from each pixel in an image. This is a common way to hide data in Steganography.";
this.infoURL = "https://wikipedia.org/wiki/Bit_numbering#Least_significant_bit_in_digital_steganography";
this.description =
"Extracts the Least Significant Bit data from each pixel in an image. This is a common way to hide data in Steganography.";
this.infoURL =
"https://wikipedia.org/wiki/Bit_numbering#Least_significant_bit_in_digital_steganography";
this.inputType = "ArrayBuffer";
this.outputType = "byteArray";
this.args = [
@ -57,8 +58,8 @@ class ExtractLSB extends Operation {
{
name: "Bit",
type: "number",
value: 0
}
value: 0,
},
];
}
@ -68,21 +69,27 @@ class ExtractLSB extends Operation {
* @returns {byteArray}
*/
async run(input, args) {
if (!isImage(input)) throw new OperationError("Please enter a valid image file.");
if (!isImage(input))
throw new OperationError("Please enter a valid image file.");
const bit = 7 - args.pop(),
pixelOrder = args.pop(),
colours = args.filter(option => option !== "").map(option => COLOUR_OPTIONS.indexOf(option)),
colours = args
.filter((option) => option !== "")
.map((option) => COLOUR_OPTIONS.indexOf(option)),
parsedImage = await Jimp.read(input),
width = parsedImage.bitmap.width,
height = parsedImage.bitmap.height,
rgba = parsedImage.bitmap.data;
if (bit < 0 || bit > 7) {
throw new OperationError("Error: Bit argument must be between 0 and 7");
throw new OperationError(
"Error: Bit argument must be between 0 and 7",
);
}
let i, combinedBinary = "";
let i,
combinedBinary = "";
if (pixelOrder === "Row") {
for (i = 0; i < rgba.length; i += 4) {
@ -106,7 +113,6 @@ class ExtractLSB extends Operation {
return fromBinary(combinedBinary);
}
}
const COLOUR_OPTIONS = ["R", "G", "B", "A"];

View File

@ -7,15 +7,14 @@
import Operation from "../Operation.mjs";
import OperationError from "../errors/OperationError.mjs";
import { isImage } from "../lib/FileType.mjs";
import Jimp from "jimp/es/index.js";
import { Jimp } from "jimp";
import {RGBA_DELIM_OPTIONS} from "../lib/Delim.mjs";
import { RGBA_DELIM_OPTIONS } from "../lib/Delim.mjs";
/**
* Extract RGBA operation
*/
class ExtractRGBA extends Operation {
/**
* ExtractRGBA constructor
*/
@ -24,7 +23,8 @@ class ExtractRGBA extends Operation {
this.name = "Extract RGBA";
this.module = "Image";
this.description = "Extracts each pixel's RGBA value in an image. These are sometimes used in Steganography to hide text or data.";
this.description =
"Extracts each pixel's RGBA value in an image. These are sometimes used in Steganography to hide text or data.";
this.infoURL = "https://wikipedia.org/wiki/RGBA_color_space";
this.inputType = "ArrayBuffer";
this.outputType = "string";
@ -32,13 +32,13 @@ class ExtractRGBA extends Operation {
{
name: "Delimiter",
type: "editableOption",
value: RGBA_DELIM_OPTIONS
value: RGBA_DELIM_OPTIONS,
},
{
name: "Include Alpha",
type: "boolean",
value: true
}
value: true,
},
];
}
@ -48,18 +48,20 @@ class ExtractRGBA extends Operation {
* @returns {string}
*/
async run(input, args) {
if (!isImage(input)) throw new OperationError("Please enter a valid image file.");
if (!isImage(input))
throw new OperationError("Please enter a valid image file.");
const delimiter = args[0],
includeAlpha = args[1],
parsedImage = await Jimp.read(input);
let bitmap = parsedImage.bitmap.data;
bitmap = includeAlpha ? bitmap : bitmap.filter((val, idx) => idx % 4 !== 3);
bitmap = includeAlpha
? bitmap
: bitmap.filter((val, idx) => idx % 4 !== 3);
return bitmap.join(delimiter);
}
}
export default ExtractRGBA;

View File

@ -9,13 +9,12 @@ import OperationError from "../errors/OperationError.mjs";
import { isImage } from "../lib/FileType.mjs";
import { toBase64 } from "../lib/Base64.mjs";
import { isWorkerEnvironment } from "../Utils.mjs";
import Jimp from "jimp/es/index.js";
import { Jimp, JimpMime } from "jimp";
/**
* Flip Image operation
*/
class FlipImage extends Operation {
/**
* FlipImage constructor
*/
@ -33,8 +32,8 @@ class FlipImage extends Operation {
{
name: "Axis",
type: "option",
value: ["Horizontal", "Vertical"]
}
value: ["Horizontal", "Vertical"],
},
];
}
@ -68,10 +67,10 @@ class FlipImage extends Operation {
}
let imageBuffer;
if (image.getMIME() === "image/gif") {
imageBuffer = await image.getBufferAsync(Jimp.MIME_PNG);
if (image.mime === "image/gif") {
imageBuffer = await image.getBuffer(JimpMime.png);
} else {
imageBuffer = await image.getBufferAsync(Jimp.AUTO);
imageBuffer = await image.getBuffer(image.mime);
}
return imageBuffer.buffer;
} catch (err) {
@ -95,7 +94,6 @@ class FlipImage extends Operation {
return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
}
}
export default FlipImage;

View File

@ -7,16 +7,15 @@
import Operation from "../Operation.mjs";
import OperationError from "../errors/OperationError.mjs";
import Utils from "../Utils.mjs";
import {isImage} from "../lib/FileType.mjs";
import {toBase64} from "../lib/Base64.mjs";
import {isWorkerEnvironment} from "../Utils.mjs";
import Jimp from "jimp/es/index.js";
import { isImage } from "../lib/FileType.mjs";
import { toBase64 } from "../lib/Base64.mjs";
import { isWorkerEnvironment } from "../Utils.mjs";
import { Jimp, JimpMime, ResizeStrategy, rgbaToInt } from "jimp";
/**
* Generate Image operation
*/
class GenerateImage extends Operation {
/**
* GenerateImage constructor
*/
@ -25,27 +24,28 @@ class GenerateImage extends Operation {
this.name = "Generate Image";
this.module = "Image";
this.description = "Generates an image using the input as pixel values.";
this.description =
"Generates an image using the input as pixel values.";
this.infoURL = "";
this.inputType = "ArrayBuffer";
this.outputType = "ArrayBuffer";
this.presentType = "html";
this.args = [
{
"name": "Mode",
"type": "option",
"value": ["Greyscale", "RG", "RGB", "RGBA", "Bits"]
name: "Mode",
type: "option",
value: ["Greyscale", "RG", "RGB", "RGBA", "Bits"],
},
{
"name": "Pixel Scale Factor",
"type": "number",
"value": 8,
name: "Pixel Scale Factor",
type: "number",
value: 8,
},
{
"name": "Pixels per row",
"type": "number",
"value": 64,
}
name: "Pixels per row",
type: "number",
value: 64,
},
];
}
@ -67,21 +67,23 @@ class GenerateImage extends Operation {
}
const bytePerPixelMap = {
"Greyscale": 1,
"RG": 2,
"RGB": 3,
"RGBA": 4,
"Bits": 1/8,
Greyscale: 1,
RG: 2,
RGB: 3,
RGBA: 4,
Bits: 1 / 8,
};
const bytesPerPixel = bytePerPixelMap[mode];
if (bytesPerPixel > 0 && input.length % bytesPerPixel !== 0) {
throw new OperationError(`Number of bytes is not a divisor of ${bytesPerPixel}`);
if (bytesPerPixel > 0 && input.length % bytesPerPixel !== 0) {
throw new OperationError(
`Number of bytes is not a divisor of ${bytesPerPixel}`,
);
}
const height = Math.ceil(input.length / bytesPerPixel / width);
const image = await new Jimp(width, height, (err, image) => {});
const image = new Jimp({ width, height });
if (isWorkerEnvironment())
self.sendStatusMessage("Generating image from data...");
@ -94,8 +96,8 @@ class GenerateImage extends Operation {
const x = index % width;
const y = Math.floor(index / width);
const value = curByte[k] === "0" ? 0xFF : 0x00;
const pixel = Jimp.rgbaToInt(value, value, value, 0xFF);
const value = curByte[k] === "0" ? 0xff : 0x00;
const pixel = rgbaToInt(value, value, value, 0xff);
image.setPixelColor(pixel, x, y);
}
}
@ -109,7 +111,7 @@ class GenerateImage extends Operation {
let red = 0x00;
let green = 0x00;
let blue = 0x00;
let alpha = 0xFF;
let alpha = 0xff;
switch (mode) {
case "Greyscale":
@ -139,10 +141,12 @@ class GenerateImage extends Operation {
}
try {
const pixel = Jimp.rgbaToInt(red, green, blue, alpha);
const pixel = rgbaToInt(red, green, blue, alpha);
image.setPixelColor(pixel, x, y);
} catch (err) {
throw new OperationError(`Error while generating image from pixel values. (${err})`);
throw new OperationError(
`Error while generating image from pixel values. (${err})`,
);
}
}
}
@ -151,11 +155,15 @@ class GenerateImage extends Operation {
if (isWorkerEnvironment())
self.sendStatusMessage("Scaling image...");
image.scaleToFit(width*scale, height*scale, Jimp.RESIZE_NEAREST_NEIGHBOR);
image.scaleToFit(
width * scale,
height * scale,
ResizeStrategy.NEAREST_NEIGHBOR,
);
}
try {
const imageBuffer = await image.getBufferAsync(Jimp.MIME_PNG);
const imageBuffer = await image.getBuffer(JimpMime.png);
return imageBuffer.buffer;
} catch (err) {
throw new OperationError(`Error generating image. (${err})`);
@ -178,7 +186,6 @@ class GenerateImage extends Operation {
return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
}
}
export default GenerateImage;

View File

@ -9,13 +9,12 @@ import OperationError from "../errors/OperationError.mjs";
import { isImage } from "../lib/FileType.mjs";
import { toBase64 } from "../lib/Base64.mjs";
import { isWorkerEnvironment } from "../Utils.mjs";
import Jimp from "jimp/es/index.js";
import { Jimp, JimpMime } from "jimp";
/**
* Image Brightness / Contrast operation
*/
class ImageBrightnessContrast extends Operation {
/**
* ImageBrightnessContrast constructor
*/
@ -35,15 +34,15 @@ class ImageBrightnessContrast extends Operation {
type: "number",
value: 0,
min: -100,
max: 100
max: 100,
},
{
name: "Contrast",
type: "number",
value: 0,
min: -100,
max: 100
}
max: 100,
},
];
}
@ -77,14 +76,16 @@ class ImageBrightnessContrast extends Operation {
}
let imageBuffer;
if (image.getMIME() === "image/gif") {
imageBuffer = await image.getBufferAsync(Jimp.MIME_PNG);
if (image.mime === "image/gif") {
imageBuffer = await image.getBuffer(JimpMime.png);
} else {
imageBuffer = await image.getBufferAsync(Jimp.AUTO);
imageBuffer = await image.getBuffer(image.mime);
}
return imageBuffer.buffer;
} catch (err) {
throw new OperationError(`Error adjusting image brightness or contrast. (${err})`);
throw new OperationError(
`Error adjusting image brightness or contrast. (${err})`,
);
}
}
@ -104,7 +105,6 @@ class ImageBrightnessContrast extends Operation {
return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
}
}
export default ImageBrightnessContrast;

View File

@ -9,13 +9,12 @@ import OperationError from "../errors/OperationError.mjs";
import { isImage } from "../lib/FileType.mjs";
import { toBase64 } from "../lib/Base64.mjs";
import { isWorkerEnvironment } from "../Utils.mjs";
import Jimp from "jimp/es/index.js";
import { Jimp, JimpMime } from "jimp";
/**
* Image Filter operation
*/
class ImageFilter extends Operation {
/**
* ImageFilter constructor
*/
@ -33,11 +32,8 @@ class ImageFilter extends Operation {
{
name: "Filter type",
type: "option",
value: [
"Greyscale",
"Sepia"
]
}
value: ["Greyscale", "Sepia"],
},
];
}
@ -60,7 +56,11 @@ class ImageFilter extends Operation {
}
try {
if (isWorkerEnvironment())
self.sendStatusMessage("Applying " + filterType.toLowerCase() + " filter to image...");
self.sendStatusMessage(
"Applying " +
filterType.toLowerCase() +
" filter to image...",
);
if (filterType === "Greyscale") {
image.greyscale();
} else {
@ -68,14 +68,16 @@ class ImageFilter extends Operation {
}
let imageBuffer;
if (image.getMIME() === "image/gif") {
imageBuffer = await image.getBufferAsync(Jimp.MIME_PNG);
if (image.mime === "image/gif") {
imageBuffer = await image.getBuffer(JimpMime.png);
} else {
imageBuffer = await image.getBufferAsync(Jimp.AUTO);
imageBuffer = await image.getBuffer(image.mime);
}
return imageBuffer.buffer;
} catch (err) {
throw new OperationError(`Error applying filter to image. (${err})`);
throw new OperationError(
`Error applying filter to image. (${err})`,
);
}
}
@ -95,7 +97,6 @@ class ImageFilter extends Operation {
return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
}
}
export default ImageFilter;

View File

@ -9,13 +9,12 @@ import OperationError from "../errors/OperationError.mjs";
import { isImage } from "../lib/FileType.mjs";
import { toBase64 } from "../lib/Base64.mjs";
import { isWorkerEnvironment } from "../Utils.mjs";
import Jimp from "jimp/es/index.js";
import { Jimp, JimpMime } from "jimp";
/**
* Image Hue/Saturation/Lightness operation
*/
class ImageHueSaturationLightness extends Operation {
/**
* ImageHueSaturationLightness constructor
*/
@ -24,7 +23,8 @@ class ImageHueSaturationLightness extends Operation {
this.name = "Image Hue/Saturation/Lightness";
this.module = "Image";
this.description = "Adjusts the hue / saturation / lightness (HSL) values of an image.";
this.description =
"Adjusts the hue / saturation / lightness (HSL) values of an image.";
this.infoURL = "";
this.inputType = "ArrayBuffer";
this.outputType = "ArrayBuffer";
@ -35,22 +35,22 @@ class ImageHueSaturationLightness extends Operation {
type: "number",
value: 0,
min: -360,
max: 360
max: 360,
},
{
name: "Saturation",
type: "number",
value: 0,
min: -100,
max: 100
max: 100,
},
{
name: "Lightness",
type: "number",
value: 0,
min: -100,
max: 100
}
max: 100,
},
];
}
@ -79,8 +79,8 @@ class ImageHueSaturationLightness extends Operation {
image.colour([
{
apply: "hue",
params: [hue]
}
params: [hue],
},
]);
}
if (saturation !== 0) {
@ -89,8 +89,8 @@ class ImageHueSaturationLightness extends Operation {
image.colour([
{
apply: "saturate",
params: [saturation]
}
params: [saturation],
},
]);
}
if (lightness !== 0) {
@ -99,20 +99,22 @@ class ImageHueSaturationLightness extends Operation {
image.colour([
{
apply: "lighten",
params: [lightness]
}
params: [lightness],
},
]);
}
let imageBuffer;
if (image.getMIME() === "image/gif") {
imageBuffer = await image.getBufferAsync(Jimp.MIME_PNG);
if (image.mime === "image/gif") {
imageBuffer = await image.getBuffer(JimpMime.png);
} else {
imageBuffer = await image.getBufferAsync(Jimp.AUTO);
imageBuffer = await image.getBuffer(image.mime);
}
return imageBuffer.buffer;
} catch (err) {
throw new OperationError(`Error adjusting image hue / saturation / lightness. (${err})`);
throw new OperationError(
`Error adjusting image hue / saturation / lightness. (${err})`,
);
}
}

View File

@ -9,13 +9,12 @@ import OperationError from "../errors/OperationError.mjs";
import { isImage } from "../lib/FileType.mjs";
import { toBase64 } from "../lib/Base64.mjs";
import { isWorkerEnvironment } from "../Utils.mjs";
import Jimp from "jimp/es/index.js";
import { Jimp, JimpMime } from "jimp";
/**
* Image Opacity operation
*/
class ImageOpacity extends Operation {
/**
* ImageOpacity constructor
*/
@ -35,8 +34,8 @@ class ImageOpacity extends Operation {
type: "number",
value: 100,
min: 0,
max: 100
}
max: 100,
},
];
}
@ -63,10 +62,10 @@ class ImageOpacity extends Operation {
image.opacity(opacity / 100);
let imageBuffer;
if (image.getMIME() === "image/gif") {
imageBuffer = await image.getBufferAsync(Jimp.MIME_PNG);
if (image.mime === "image/gif") {
imageBuffer = await image.getBuffer(JimpMime.png);
} else {
imageBuffer = await image.getBufferAsync(Jimp.AUTO);
imageBuffer = await image.getBuffer(image.mime);
}
return imageBuffer.buffer;
} catch (err) {
@ -90,7 +89,6 @@ class ImageOpacity extends Operation {
return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
}
}
export default ImageOpacity;

View File

@ -9,13 +9,12 @@ import OperationError from "../errors/OperationError.mjs";
import { isImage } from "../lib/FileType.mjs";
import { toBase64 } from "../lib/Base64.mjs";
import { isWorkerEnvironment } from "../Utils.mjs";
import Jimp from "jimp/es/index.js";
import { Jimp, JimpMime } from "jimp";
/**
* Invert Image operation
*/
class InvertImage extends Operation {
/**
* InvertImage constructor
*/
@ -54,10 +53,10 @@ class InvertImage extends Operation {
image.invert();
let imageBuffer;
if (image.getMIME() === "image/gif") {
imageBuffer = await image.getBufferAsync(Jimp.MIME_PNG);
if (image.mime === "image/gif") {
imageBuffer = await image.getBuffer(JimpMime.png);
} else {
imageBuffer = await image.getBufferAsync(Jimp.AUTO);
imageBuffer = await image.getBuffer(image.mime);
}
return imageBuffer.buffer;
} catch (err) {
@ -81,7 +80,6 @@ class InvertImage extends Operation {
return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
}
}
export default InvertImage;

View File

@ -8,13 +8,12 @@ import Operation from "../Operation.mjs";
import OperationError from "../errors/OperationError.mjs";
import { isImage } from "../lib/FileType.mjs";
import { toBase64 } from "../lib/Base64.mjs";
import Jimp from "jimp/es/index.js";
import { Jimp, JimpMime } from "jimp";
/**
* Normalise Image operation
*/
class NormaliseImage extends Operation {
/**
* NormaliseImage constructor
*/
@ -27,7 +26,7 @@ class NormaliseImage extends Operation {
this.infoURL = "";
this.inputType = "ArrayBuffer";
this.outputType = "ArrayBuffer";
this.presentType= "html";
this.presentType = "html";
this.args = [];
}
@ -52,10 +51,10 @@ class NormaliseImage extends Operation {
image.normalize();
let imageBuffer;
if (image.getMIME() === "image/gif") {
imageBuffer = await image.getBufferAsync(Jimp.MIME_PNG);
if (image.mime === "image/gif") {
imageBuffer = await image.getBuffer(JimpMime.png);
} else {
imageBuffer = await image.getBufferAsync(Jimp.AUTO);
imageBuffer = await image.getBuffer(image.mime);
}
return imageBuffer.buffer;
} catch (err) {
@ -79,7 +78,6 @@ class NormaliseImage extends Operation {
return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
}
}
export default NormaliseImage;

View File

@ -13,7 +13,6 @@ import { parseQrCode } from "../lib/QRCode.mjs";
* Parse QR Code operation
*/
class ParseQRCode extends Operation {
/**
* ParseQRCode constructor
*/
@ -22,24 +21,26 @@ class ParseQRCode extends Operation {
this.name = "Parse QR Code";
this.module = "Image";
this.description = "Reads an image file and attempts to detect and read a Quick Response (QR) code from the image.<br><br><u>Normalise Image</u><br>Attempts to normalise the image before parsing it to improve detection of a QR code.";
this.description =
"Reads an image file and attempts to detect and read a Quick Response (QR) code from the image.<br><br><u>Normalise Image</u><br>Attempts to normalise the image before parsing it to improve detection of a QR code.";
this.infoURL = "https://wikipedia.org/wiki/QR_code";
this.inputType = "ArrayBuffer";
this.outputType = "string";
this.args = [
{
"name": "Normalise image",
"type": "boolean",
"value": false
}
name: "Normalise image",
type: "boolean",
value: false,
},
];
this.checks = [
{
"pattern": "^(?:\\xff\\xd8\\xff|\\x89\\x50\\x4e\\x47|\\x47\\x49\\x46|.{8}\\x57\\x45\\x42\\x50|\\x42\\x4d)",
"flags": "",
"args": [false],
"useful": true
}
pattern:
"^(?:\\xff\\xd8\\xff|\\x89\\x50\\x4e\\x47|\\x47\\x49\\x46|.{8}\\x57\\x45\\x42\\x50|\\x42\\x4d)",
flags: "",
args: [false],
useful: true,
},
];
}
@ -54,9 +55,8 @@ class ParseQRCode extends Operation {
if (!isImage(input)) {
throw new OperationError("Invalid file type.");
}
return await parseQrCode(input, normalise);
return parseQrCode(input, normalise);
}
}
export default ParseQRCode;

View File

@ -10,13 +10,12 @@ import Utils from "../Utils.mjs";
import { isImage } from "../lib/FileType.mjs";
import { runHash } from "../lib/Hash.mjs";
import { toBase64 } from "../lib/Base64.mjs";
import Jimp from "jimp/es/index.js";
import { Jimp } from "jimp";
/**
* Randomize Colour Palette operation
*/
class RandomizeColourPalette extends Operation {
/**
* RandomizeColourPalette constructor
*/
@ -25,7 +24,8 @@ class RandomizeColourPalette extends Operation {
this.name = "Randomize Colour Palette";
this.module = "Image";
this.description = "Randomizes each colour in an image's colour palette. This can often reveal text or symbols that were previously a very similar colour to their surroundings, a technique sometimes used in Steganography.";
this.description =
"Randomizes each colour in an image's colour palette. This can often reveal text or symbols that were previously a very similar colour to their surroundings, a technique sometimes used in Steganography.";
this.infoURL = "https://wikipedia.org/wiki/Indexed_color";
this.inputType = "ArrayBuffer";
this.outputType = "ArrayBuffer";
@ -34,8 +34,8 @@ class RandomizeColourPalette extends Operation {
{
name: "Seed",
type: "string",
value: ""
}
value: "",
},
];
}
@ -45,23 +45,24 @@ class RandomizeColourPalette extends Operation {
* @returns {ArrayBuffer}
*/
async run(input, args) {
if (!isImage(input)) throw new OperationError("Please enter a valid image file.");
if (!isImage(input))
throw new OperationError("Please enter a valid image file.");
const seed = args[0] || (Math.random().toString().substr(2)),
const seed = args[0] || Math.random().toString().substr(2),
parsedImage = await Jimp.read(input),
width = parsedImage.bitmap.width,
height = parsedImage.bitmap.height;
let rgbString, rgbHash, rgbHex;
parsedImage.scan(0, 0, width, height, function(x, y, idx) {
rgbString = this.bitmap.data.slice(idx, idx+3).join(".");
parsedImage.scan(0, 0, width, height, function (x, y, idx) {
rgbString = this.bitmap.data.slice(idx, idx + 3).join(".");
rgbHash = runHash("md5", Utils.strToArrayBuffer(seed + rgbString));
rgbHex = rgbHash.substr(0, 6) + "ff";
parsedImage.setPixelColor(parseInt(rgbHex, 16), x, y);
});
const imageBuffer = await parsedImage.getBufferAsync(Jimp.AUTO);
const imageBuffer = await parsedImage.getBuffer(parsedImage.mime);
return new Uint8Array(imageBuffer).buffer;
}
@ -77,7 +78,6 @@ class RandomizeColourPalette extends Operation {
return `<img src="data:${type};base64,${toBase64(data)}">`;
}
}
export default RandomizeColourPalette;

View File

@ -9,13 +9,12 @@ import OperationError from "../errors/OperationError.mjs";
import { isImage } from "../lib/FileType.mjs";
import { toBase64 } from "../lib/Base64.mjs";
import { isWorkerEnvironment } from "../Utils.mjs";
import Jimp from "jimp/es/index.js";
import { Jimp, JimpMime, ResizeStrategy } from "jimp";
/**
* Resize Image operation
*/
class ResizeImage extends Operation {
/**
* ResizeImage constructor
*/
@ -24,7 +23,8 @@ class ResizeImage extends Operation {
this.name = "Resize Image";
this.module = "Image";
this.description = "Resizes an image to the specified width and height values.";
this.description =
"Resizes an image to the specified width and height values.";
this.infoURL = "https://wikipedia.org/wiki/Image_scaling";
this.inputType = "ArrayBuffer";
this.outputType = "ArrayBuffer";
@ -34,23 +34,23 @@ class ResizeImage extends Operation {
name: "Width",
type: "number",
value: 100,
min: 1
min: 1,
},
{
name: "Height",
type: "number",
value: 100,
min: 1
min: 1,
},
{
name: "Unit type",
type: "option",
value: ["Pixels", "Percent"]
value: ["Pixels", "Percent"],
},
{
name: "Maintain aspect ratio",
type: "boolean",
value: false
value: false,
},
{
name: "Resizing algorithm",
@ -60,10 +60,10 @@ class ResizeImage extends Operation {
"Bilinear",
"Bicubic",
"Hermite",
"Bezier"
"Bezier",
],
defaultIndex: 1
}
defaultIndex: 1,
},
];
}
@ -80,11 +80,11 @@ class ResizeImage extends Operation {
resizeAlg = args[4];
const resizeMap = {
"Nearest Neighbour": Jimp.RESIZE_NEAREST_NEIGHBOR,
"Bilinear": Jimp.RESIZE_BILINEAR,
"Bicubic": Jimp.RESIZE_BICUBIC,
"Hermite": Jimp.RESIZE_HERMITE,
"Bezier": Jimp.RESIZE_BEZIER
"Nearest Neighbour": ResizeStrategy.NEAREST_NEIGHBOR,
Bilinear: ResizeStrategy.BILINEAR,
Bicubic: ResizeStrategy.BICUBIC,
Hermite: ResizeStrategy.HERMITE,
Bezier: ResizeStrategy.BEZIER,
};
if (!isImage(input)) {
@ -99,8 +99,8 @@ class ResizeImage extends Operation {
}
try {
if (unit === "Percent") {
width = image.getWidth() * (width / 100);
height = image.getHeight() * (height / 100);
width = image.width * (width / 100);
height = image.height * (height / 100);
}
if (isWorkerEnvironment())
@ -112,10 +112,10 @@ class ResizeImage extends Operation {
}
let imageBuffer;
if (image.getMIME() === "image/gif") {
imageBuffer = await image.getBufferAsync(Jimp.MIME_PNG);
if (image.mime === "image/gif") {
imageBuffer = await image.getBuffer(JimpMime.png);
} else {
imageBuffer = await image.getBufferAsync(Jimp.AUTO);
imageBuffer = await image.getBuffer(image.mime);
}
return imageBuffer.buffer;
} catch (err) {
@ -139,7 +139,6 @@ class ResizeImage extends Operation {
return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
}
}
export default ResizeImage;

View File

@ -9,13 +9,12 @@ import OperationError from "../errors/OperationError.mjs";
import { isImage } from "../lib/FileType.mjs";
import { toBase64 } from "../lib/Base64.mjs";
import { isWorkerEnvironment } from "../Utils.mjs";
import Jimp from "jimp/es/index.js";
import { Jimp, JimpMime } from "jimp";
/**
* Rotate Image operation
*/
class RotateImage extends Operation {
/**
* RotateImage constructor
*/
@ -24,7 +23,8 @@ class RotateImage extends Operation {
this.name = "Rotate Image";
this.module = "Image";
this.description = "Rotates an image by the specified number of degrees.";
this.description =
"Rotates an image by the specified number of degrees.";
this.infoURL = "";
this.inputType = "ArrayBuffer";
this.outputType = "ArrayBuffer";
@ -33,8 +33,8 @@ class RotateImage extends Operation {
{
name: "Rotation amount (degrees)",
type: "number",
value: 90
}
value: 90,
},
];
}
@ -62,10 +62,10 @@ class RotateImage extends Operation {
image.rotate(degrees);
let imageBuffer;
if (image.getMIME() === "image/gif") {
imageBuffer = await image.getBufferAsync(Jimp.MIME_PNG);
if (image.mime === "image/gif") {
imageBuffer = await image.getBuffer(JimpMime.png);
} else {
imageBuffer = await image.getBufferAsync(Jimp.AUTO);
imageBuffer = await image.getBuffer(image.mime);
}
return imageBuffer.buffer;
} catch (err) {
@ -89,7 +89,6 @@ class RotateImage extends Operation {
return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
}
}
export default RotateImage;

View File

@ -10,13 +10,12 @@ import { isImage } from "../lib/FileType.mjs";
import { toBase64 } from "../lib/Base64.mjs";
import { gaussianBlur } from "../lib/ImageManipulation.mjs";
import { isWorkerEnvironment } from "../Utils.mjs";
import Jimp from "jimp/es/index.js";
import { Jimp, JimpMime } from "jimp";
/**
* Sharpen Image operation
*/
class SharpenImage extends Operation {
/**
* SharpenImage constructor
*/
@ -35,22 +34,22 @@ class SharpenImage extends Operation {
name: "Radius",
type: "number",
value: 2,
min: 1
min: 1,
},
{
name: "Amount",
type: "number",
value: 1,
min: 0,
step: 0.1
step: 0.1,
},
{
name: "Threshold",
type: "number",
value: 10,
min: 0,
max: 100
}
max: 100,
},
];
}
@ -79,67 +78,102 @@ class SharpenImage extends Operation {
const blurMask = image.clone();
if (isWorkerEnvironment())
self.sendStatusMessage("Sharpening image... (Blurring cloned image)");
self.sendStatusMessage(
"Sharpening image... (Blurring cloned image)",
);
const blurImage = gaussianBlur(image.clone(), radius);
if (isWorkerEnvironment())
self.sendStatusMessage(
"Sharpening image... (Creating unsharp mask)",
);
blurMask.scan(
0,
0,
blurMask.bitmap.width,
blurMask.bitmap.height,
function (x, y, idx) {
const blurRed = blurImage.bitmap.data[idx];
const blurGreen = blurImage.bitmap.data[idx + 1];
const blurBlue = blurImage.bitmap.data[idx + 2];
const normalRed = this.bitmap.data[idx];
const normalGreen = this.bitmap.data[idx + 1];
const normalBlue = this.bitmap.data[idx + 2];
// Subtract blurred pixel value from normal image
this.bitmap.data[idx] =
normalRed > blurRed ? normalRed - blurRed : 0;
this.bitmap.data[idx + 1] =
normalGreen > blurGreen ? normalGreen - blurGreen : 0;
this.bitmap.data[idx + 2] =
normalBlue > blurBlue ? normalBlue - blurBlue : 0;
},
);
if (isWorkerEnvironment())
self.sendStatusMessage("Sharpening image... (Creating unsharp mask)");
blurMask.scan(0, 0, blurMask.bitmap.width, blurMask.bitmap.height, function(x, y, idx) {
const blurRed = blurImage.bitmap.data[idx];
const blurGreen = blurImage.bitmap.data[idx + 1];
const blurBlue = blurImage.bitmap.data[idx + 2];
self.sendStatusMessage(
"Sharpening image... (Merging with unsharp mask)",
);
image.scan(
0,
0,
image.bitmap.width,
image.bitmap.height,
function (x, y, idx) {
let maskRed = blurMask.bitmap.data[idx];
let maskGreen = blurMask.bitmap.data[idx + 1];
let maskBlue = blurMask.bitmap.data[idx + 2];
const normalRed = this.bitmap.data[idx];
const normalGreen = this.bitmap.data[idx + 1];
const normalBlue = this.bitmap.data[idx + 2];
const normalRed = this.bitmap.data[idx];
const normalGreen = this.bitmap.data[idx + 1];
const normalBlue = this.bitmap.data[idx + 2];
// Subtract blurred pixel value from normal image
this.bitmap.data[idx] = (normalRed > blurRed) ? normalRed - blurRed : 0;
this.bitmap.data[idx + 1] = (normalGreen > blurGreen) ? normalGreen - blurGreen : 0;
this.bitmap.data[idx + 2] = (normalBlue > blurBlue) ? normalBlue - blurBlue : 0;
});
// Calculate luminance
const maskLuminance =
0.2126 * maskRed +
0.7152 * maskGreen +
0.0722 * maskBlue;
const normalLuminance =
0.2126 * normalRed +
0.7152 * normalGreen +
0.0722 * normalBlue;
if (isWorkerEnvironment())
self.sendStatusMessage("Sharpening image... (Merging with unsharp mask)");
image.scan(0, 0, image.bitmap.width, image.bitmap.height, function(x, y, idx) {
let maskRed = blurMask.bitmap.data[idx];
let maskGreen = blurMask.bitmap.data[idx + 1];
let maskBlue = blurMask.bitmap.data[idx + 2];
let luminanceDiff;
if (maskLuminance > normalLuminance) {
luminanceDiff = maskLuminance - normalLuminance;
} else {
luminanceDiff = normalLuminance - maskLuminance;
}
const normalRed = this.bitmap.data[idx];
const normalGreen = this.bitmap.data[idx + 1];
const normalBlue = this.bitmap.data[idx + 2];
// Scale mask colours by amount
maskRed = maskRed * amount;
maskGreen = maskGreen * amount;
maskBlue = maskBlue * amount;
// Calculate luminance
const maskLuminance = (0.2126 * maskRed + 0.7152 * maskGreen + 0.0722 * maskBlue);
const normalLuminance = (0.2126 * normalRed + 0.7152 * normalGreen + 0.0722 * normalBlue);
let luminanceDiff;
if (maskLuminance > normalLuminance) {
luminanceDiff = maskLuminance - normalLuminance;
} else {
luminanceDiff = normalLuminance - maskLuminance;
}
// Scale mask colours by amount
maskRed = maskRed * amount;
maskGreen = maskGreen * amount;
maskBlue = maskBlue * amount;
// Only change pixel value if the difference is higher than threshold
if ((luminanceDiff / 255) * 100 >= threshold) {
this.bitmap.data[idx] = (normalRed + maskRed) <= 255 ? normalRed + maskRed : 255;
this.bitmap.data[idx + 1] = (normalGreen + maskGreen) <= 255 ? normalGreen + maskGreen : 255;
this.bitmap.data[idx + 2] = (normalBlue + maskBlue) <= 255 ? normalBlue + maskBlue : 255;
}
});
// Only change pixel value if the difference is higher than threshold
if ((luminanceDiff / 255) * 100 >= threshold) {
this.bitmap.data[idx] =
normalRed + maskRed <= 255
? normalRed + maskRed
: 255;
this.bitmap.data[idx + 1] =
normalGreen + maskGreen <= 255
? normalGreen + maskGreen
: 255;
this.bitmap.data[idx + 2] =
normalBlue + maskBlue <= 255
? normalBlue + maskBlue
: 255;
}
},
);
let imageBuffer;
if (image.getMIME() === "image/gif") {
imageBuffer = await image.getBufferAsync(Jimp.MIME_PNG);
if (image.mime === "image/gif") {
imageBuffer = await image.getBuffer(JimpMime.png);
} else {
imageBuffer = await image.getBufferAsync(Jimp.AUTO);
imageBuffer = await image.getBuffer(image.mime);
}
return imageBuffer.buffer;
} catch (err) {
@ -163,7 +197,6 @@ class SharpenImage extends Operation {
return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
}
}
export default SharpenImage;

View File

@ -7,14 +7,13 @@
import Operation from "../Operation.mjs";
import OperationError from "../errors/OperationError.mjs";
import Utils from "../Utils.mjs";
import {isImage} from "../lib/FileType.mjs";
import Jimp from "jimp/es/index.js";
import { isImage } from "../lib/FileType.mjs";
import { Jimp, JimpMime } from "jimp";
/**
* Split Colour Channels operation
*/
class SplitColourChannels extends Operation {
/**
* SplitColourChannels constructor
*/
@ -23,7 +22,8 @@ class SplitColourChannels extends Operation {
this.name = "Split Colour Channels";
this.module = "Image";
this.description = "Splits the given image into its red, green and blue colour channels.";
this.description =
"Splits the given image into its red, green and blue colour channels.";
this.infoURL = "https://wikipedia.org/wiki/Channel_(digital_image)";
this.inputType = "ArrayBuffer";
this.outputType = "List<File>";
@ -48,26 +48,44 @@ class SplitColourChannels extends Operation {
const split = parsedImage
.clone()
.color([
{apply: "blue", params: [-255]},
{apply: "green", params: [-255]}
{ apply: "blue", params: [-255] },
{ apply: "green", params: [-255] },
])
.getBufferAsync(Jimp.MIME_PNG);
resolve(new File([new Uint8Array((await split).values())], "red.png", {type: "image/png"}));
.getBuffer(JimpMime.png);
resolve(
new File(
[new Uint8Array((await split).values())],
"red.png",
{ type: "image/png" },
),
);
} catch (err) {
reject(new OperationError(`Could not split red channel: ${err}`));
reject(
new OperationError(`Could not split red channel: ${err}`),
);
}
});
const green = new Promise(async (resolve, reject) => {
try {
const split = parsedImage.clone()
const split = parsedImage
.clone()
.color([
{apply: "red", params: [-255]},
{apply: "blue", params: [-255]},
]).getBufferAsync(Jimp.MIME_PNG);
resolve(new File([new Uint8Array((await split).values())], "green.png", {type: "image/png"}));
{ apply: "red", params: [-255] },
{ apply: "blue", params: [-255] },
])
.getBuffer(JimpMime.png);
resolve(
new File(
[new Uint8Array((await split).values())],
"green.png",
{ type: "image/png" },
),
);
} catch (err) {
reject(new OperationError(`Could not split green channel: ${err}`));
reject(
new OperationError(`Could not split green channel: ${err}`),
);
}
});
@ -75,12 +93,21 @@ class SplitColourChannels extends Operation {
try {
const split = parsedImage
.color([
{apply: "red", params: [-255]},
{apply: "green", params: [-255]},
]).getBufferAsync(Jimp.MIME_PNG);
resolve(new File([new Uint8Array((await split).values())], "blue.png", {type: "image/png"}));
{ apply: "red", params: [-255] },
{ apply: "green", params: [-255] },
])
.getBuffer(JimpMime.png);
resolve(
new File(
[new Uint8Array((await split).values())],
"blue.png",
{ type: "image/png" },
),
);
} catch (err) {
reject(new OperationError(`Could not split blue channel: ${err}`));
reject(
new OperationError(`Could not split blue channel: ${err}`),
);
}
});
@ -96,7 +123,6 @@ class SplitColourChannels extends Operation {
async present(files) {
return await Utils.displayFilesAsHTML(files);
}
}
export default SplitColourChannels;

View File

@ -9,13 +9,12 @@ import OperationError from "../errors/OperationError.mjs";
import Utils from "../Utils.mjs";
import { isImage } from "../lib/FileType.mjs";
import { toBase64 } from "../lib/Base64.mjs";
import Jimp from "jimp/es/index.js";
import { Jimp } from "jimp";
/**
* View Bit Plane operation
*/
class ViewBitPlane extends Operation {
/**
* ViewBitPlane constructor
*/
@ -24,7 +23,8 @@ class ViewBitPlane extends Operation {
this.name = "View Bit Plane";
this.module = "Image";
this.description = "Extracts and displays a bit plane of any given image. These show only a single bit from each pixel, and can be used to hide messages in Steganography.";
this.description =
"Extracts and displays a bit plane of any given image. These show only a single bit from each pixel, and can be used to hide messages in Steganography.";
this.infoURL = "https://wikipedia.org/wiki/Bit_plane";
this.inputType = "ArrayBuffer";
this.outputType = "ArrayBuffer";
@ -33,13 +33,13 @@ class ViewBitPlane extends Operation {
{
name: "Colour",
type: "option",
value: COLOUR_OPTIONS
value: COLOUR_OPTIONS,
},
{
name: "Bit",
type: "number",
value: 0
}
value: 0,
},
];
}
@ -49,36 +49,38 @@ class ViewBitPlane extends Operation {
* @returns {ArrayBuffer}
*/
async run(input, args) {
if (!isImage(input)) throw new OperationError("Please enter a valid image file.");
if (!isImage(input))
throw new OperationError("Please enter a valid image file.");
const [colour, bit] = args,
parsedImage = await Jimp.read(input),
width = parsedImage.bitmap.width,
height = parsedImage.bitmap.height,
colourIndex = COLOUR_OPTIONS.indexOf(colour),
bitIndex = 7-bit;
bitIndex = 7 - bit;
if (bit < 0 || bit > 7) {
throw new OperationError("Error: Bit argument must be between 0 and 7");
throw new OperationError(
"Error: Bit argument must be between 0 and 7",
);
}
let pixel, bin, newPixelValue;
parsedImage.scan(0, 0, width, height, function(x, y, idx) {
parsedImage.scan(0, 0, width, height, function (x, y, idx) {
pixel = this.bitmap.data[idx + colourIndex];
bin = Utils.bin(pixel);
newPixelValue = 255;
if (bin.charAt(bitIndex) === "1") newPixelValue = 0;
for (let i=0; i < 3; i++) {
for (let i = 0; i < 3; i++) {
this.bitmap.data[idx + i] = newPixelValue;
}
this.bitmap.data[idx + 3] = 255;
});
const imageBuffer = await parsedImage.getBufferAsync(Jimp.AUTO);
const imageBuffer = await parsedImage.getBuffer(parsedImage.mime);
return new Uint8Array(imageBuffer).buffer;
}
@ -94,14 +96,8 @@ class ViewBitPlane extends Operation {
return `<img src="data:${type};base64,${toBase64(data)}">`;
}
}
const COLOUR_OPTIONS = [
"Red",
"Green",
"Blue",
"Alpha"
];
const COLOUR_OPTIONS = ["Red", "Green", "Blue", "Alpha"];
export default ViewBitPlane;