RandomizeColourPalette.mjs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**
  2. * @author Ge0rg3 [georgeomnet+cyberchef@gmail.com]
  3. * @copyright Crown Copyright 2019
  4. * @license Apache-2.0
  5. */
  6. import Operation from "../Operation.mjs";
  7. import OperationError from "../errors/OperationError.mjs";
  8. import Utils from "../Utils";
  9. import PseudoRandomNumberGenerator from "./PseudoRandomNumberGenerator.mjs";
  10. import { isImage } from "../lib/FileType";
  11. import { runHash } from "../lib/Hash.mjs";
  12. import { toBase64 } from "../lib/Base64";
  13. import jimp from "jimp";
  14. /**
  15. * Randomize Colour Palette operation
  16. */
  17. class RandomizeColourPalette extends Operation {
  18. /**
  19. * RandomizeColourPalette constructor
  20. */
  21. constructor() {
  22. super();
  23. this.name = "Randomize Colour Palette";
  24. this.module = "Image";
  25. this.description = "Randomize's 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.";
  26. this.infoURL = "https://en.wikipedia.org/wiki/Indexed_color";
  27. this.inputType = "byteArray";
  28. this.outputType = "byteArray";
  29. this.presentType = "html";
  30. this.args = [
  31. {
  32. name: "Seed",
  33. type: "string",
  34. value: ""
  35. }
  36. ];
  37. }
  38. /**
  39. * @param {byteArray} input
  40. * @param {Object[]} args
  41. * @returns {byteArray}
  42. */
  43. async run(input, args) {
  44. if (!isImage(input)) throw new OperationError("Please enter a valid image file.");
  45. const seed = args[0] || (new PseudoRandomNumberGenerator()).run("", [5, "Hex"]),
  46. parsedImage = await jimp.read(Buffer.from(input)),
  47. width = parsedImage.bitmap.width,
  48. height = parsedImage.bitmap.height;
  49. let rgbString, rgbHash, rgbHex;
  50. parsedImage.scan(0, 0, width, height, function(x, y, idx) {
  51. rgbString = this.bitmap.data.slice(idx, idx+3).join(".");
  52. rgbHash = runHash("md5", Utils.strToArrayBuffer(seed + rgbString));
  53. rgbHex = rgbHash.substr(0, 6) + "ff";
  54. parsedImage.setPixelColor(parseInt(rgbHex, 16), x, y);
  55. });
  56. const imageBuffer = await parsedImage.getBufferAsync(jimp.AUTO);
  57. return Array.from(imageBuffer);
  58. }
  59. /**
  60. * Displays the extracted data as an image for web apps.
  61. * @param {byteArray} data
  62. * @returns {html}
  63. */
  64. present(data) {
  65. if (!data.length) return "";
  66. const type = isImage(data);
  67. return `<img src="data:${type};base64,${toBase64(data)}">`;
  68. }
  69. }
  70. export default RandomizeColourPalette;