ImageBrightnessContrast.mjs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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. let imageBuffer;
  72. if (image.getMIME() === "image/gif") {
  73. imageBuffer = await image.getBufferAsync(jimp.MIME_PNG);
  74. } else {
  75. imageBuffer = await image.getBufferAsync(jimp.AUTO);
  76. }
  77. return [...imageBuffer];
  78. } catch (err) {
  79. throw new OperationError(`Error adjusting image brightness or contrast. (${err})`);
  80. }
  81. }
  82. /**
  83. * Displays the image using HTML for web apps
  84. * @param {byteArray} data
  85. * @returns {html}
  86. */
  87. present(data) {
  88. if (!data.length) return "";
  89. const type = isImage(data);
  90. if (!type) {
  91. throw new OperationError("Invalid file type.");
  92. }
  93. return `<img src="data:${type};base64,${toBase64(data)}">`;
  94. }
  95. }
  96. export default ImageBrightnessContrast;