RotateImage.mjs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /**
  2. * @author j433866 [j433866@gmail.com]
  3. * @copyright Crown Copyright 2018
  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 jimplib from "jimp/es/index.js";
  12. const jimp = jimplib.default ? jimplib.default : jimplib;
  13. /**
  14. * Rotate Image operation
  15. */
  16. class RotateImage extends Operation {
  17. /**
  18. * RotateImage constructor
  19. */
  20. constructor() {
  21. super();
  22. this.name = "Rotate Image";
  23. this.module = "Image";
  24. this.description = "Rotates an image by the specified number of degrees.";
  25. this.infoURL = "";
  26. this.inputType = "ArrayBuffer";
  27. this.outputType = "ArrayBuffer";
  28. this.presentType = "html";
  29. this.args = [
  30. {
  31. name: "Rotation amount (degrees)",
  32. type: "number",
  33. value: 90
  34. }
  35. ];
  36. }
  37. /**
  38. * @param {ArrayBuffer} input
  39. * @param {Object[]} args
  40. * @returns {byteArray}
  41. */
  42. async run(input, args) {
  43. const [degrees] = args;
  44. if (!isImage(input)) {
  45. throw new OperationError("Invalid file type.");
  46. }
  47. let image;
  48. try {
  49. image = await jimp.read(input);
  50. } catch (err) {
  51. throw new OperationError(`Error loading image. (${err})`);
  52. }
  53. try {
  54. if (isWorkerEnvironment())
  55. self.sendStatusMessage("Rotating image...");
  56. image.rotate(degrees);
  57. let imageBuffer;
  58. if (image.getMIME() === "image/gif") {
  59. imageBuffer = await image.getBufferAsync(jimp.MIME_PNG);
  60. } else {
  61. imageBuffer = await image.getBufferAsync(jimp.AUTO);
  62. }
  63. return imageBuffer.buffer;
  64. } catch (err) {
  65. throw new OperationError(`Error rotating image. (${err})`);
  66. }
  67. }
  68. /**
  69. * Displays the rotated image using HTML for web apps
  70. * @param {ArrayBuffer} data
  71. * @returns {html}
  72. */
  73. present(data) {
  74. if (!data.byteLength) return "";
  75. const dataArray = new Uint8Array(data);
  76. const type = isImage(dataArray);
  77. if (!type) {
  78. throw new OperationError("Invalid file type.");
  79. }
  80. return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
  81. }
  82. }
  83. export default RotateImage;