ImageBrightnessContrast.mjs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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.mjs";
  10. import jimp from "jimp";
  11. /**
  12. * Image Brightness / Contrast operation
  13. */
  14. class ImageBrightnessContrast extends Operation {
  15. /**
  16. * ImageBrightnessContrast constructor
  17. */
  18. constructor() {
  19. super();
  20. this.name = "Image Brightness / Contrast";
  21. this.module = "Image";
  22. this.description = "Adjust the brightness or contrast of an image.";
  23. this.infoURL = "";
  24. this.inputType = "byteArray";
  25. this.outputType = "byteArray";
  26. this.presentType = "html";
  27. this.args = [
  28. {
  29. name: "Brightness",
  30. type: "number",
  31. value: 0,
  32. min: -100,
  33. max: 100
  34. },
  35. {
  36. name: "Contrast",
  37. type: "number",
  38. value: 0,
  39. min: -100,
  40. max: 100
  41. }
  42. ];
  43. }
  44. /**
  45. * @param {byteArray} input
  46. * @param {Object[]} args
  47. * @returns {byteArray}
  48. */
  49. async run(input, args) {
  50. const [brightness, contrast] = args;
  51. if (!isImage(input)) {
  52. throw new OperationError("Invalid file type.");
  53. }
  54. let image;
  55. try {
  56. image = await jimp.read(Buffer.from(input));
  57. } catch (err) {
  58. throw new OperationError(`Error loading image. (${err})`);
  59. }
  60. try {
  61. if (brightness !== 0) {
  62. if (ENVIRONMENT_IS_WORKER())
  63. self.sendStatusMessage("Changing image brightness...");
  64. image.brightness(brightness / 100);
  65. }
  66. if (contrast !== 0) {
  67. if (ENVIRONMENT_IS_WORKER())
  68. self.sendStatusMessage("Changing image contrast...");
  69. image.contrast(contrast / 100);
  70. }
  71. const imageBuffer = await image.getBufferAsync(jimp.AUTO);
  72. return [...imageBuffer];
  73. } catch (err) {
  74. throw new OperationError(`Error adjusting image brightness or contrast. (${err})`);
  75. }
  76. }
  77. /**
  78. * Displays the image using HTML for web apps
  79. * @param {byteArray} data
  80. * @returns {html}
  81. */
  82. present(data) {
  83. if (!data.length) return "";
  84. const type = isImage(data);
  85. if (!type) {
  86. throw new OperationError("Invalid file type.");
  87. }
  88. return `<img src="data:${type};base64,${toBase64(data)}">`;
  89. }
  90. }
  91. export default ImageBrightnessContrast;