RotateImage.mjs 2.1 KB

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