InvertImage.mjs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 Magic from "../lib/Magic";
  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. const type = Magic.magicFileType(input);
  36. if (!type || type.mime.indexOf("image") !== 0) {
  37. throw new OperationError("Invalid input file format.");
  38. }
  39. const image = await jimp.read(Buffer.from(input));
  40. if (ENVIRONMENT_IS_WORKER())
  41. self.sendStatusMessage("Inverting image...");
  42. image.invert();
  43. const imageBuffer = await image.getBufferAsync(jimp.AUTO);
  44. return [...imageBuffer];
  45. }
  46. /**
  47. * Displays the inverted image using HTML for web apps
  48. * @param {byteArray} data
  49. * @returns {html}
  50. */
  51. present(data) {
  52. if (!data.length) return "";
  53. let dataURI = "data:";
  54. const type = Magic.magicFileType(data);
  55. if (type && type.mime.indexOf("image") === 0){
  56. dataURI += type.mime + ";";
  57. } else {
  58. throw new OperationError("Invalid file type.");
  59. }
  60. dataURI += "base64," + toBase64(data);
  61. return "<img src='" + dataURI + "'>";
  62. }
  63. }
  64. export default InvertImage;