ImageOpacity.mjs 2.5 KB

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