InvertImage.mjs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**
  2. * @author j433866 [j433866@gmail.com]
  3. * @copyright Crown Copyright 2019
  4. * @license Apache-2.0
  5. */
  6. import Operation from "../Operation";
  7. import OperationError from "../errors/OperationError";
  8. import { isImage } from "../lib/FileType";
  9. import { toBase64 } from "../lib/Base64";
  10. import jimp from "jimp";
  11. /**
  12. * Invert Image operation
  13. */
  14. class InvertImage extends Operation {
  15. /**
  16. * InvertImage constructor
  17. */
  18. constructor() {
  19. super();
  20. this.name = "Invert Image";
  21. this.module = "Image";
  22. this.description = "Invert the colours of an image.";
  23. this.infoURL = "";
  24. this.inputType = "byteArray";
  25. this.outputType = "byteArray";
  26. this.presentType = "html";
  27. this.args = [];
  28. }
  29. /**
  30. * @param {byteArray} input
  31. * @param {Object[]} args
  32. * @returns {byteArray}
  33. */
  34. async run(input, args) {
  35. if (!isImage(input)) {
  36. throw new OperationError("Invalid input file format.");
  37. }
  38. let image;
  39. try {
  40. image = await jimp.read(Buffer.from(input));
  41. } catch (err) {
  42. throw new OperationError(`Error loading image. (${err})`);
  43. }
  44. try {
  45. if (ENVIRONMENT_IS_WORKER())
  46. self.sendStatusMessage("Inverting image...");
  47. image.invert();
  48. let imageBuffer;
  49. if (image.getMIME() === "image/gif") {
  50. imageBuffer = await image.getBufferAsync(jimp.MIME_PNG);
  51. } else {
  52. imageBuffer = await image.getBufferAsync(jimp.AUTO);
  53. }
  54. return [...imageBuffer];
  55. } catch (err) {
  56. throw new OperationError(`Error inverting image. (${err})`);
  57. }
  58. }
  59. /**
  60. * Displays the inverted image using HTML 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. if (!type) {
  68. throw new OperationError("Invalid file type.");
  69. }
  70. return `<img src="data:${type};base64,${toBase64(data)}">`;
  71. }
  72. }
  73. export default InvertImage;