RenderImage.mjs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. /**
  2. * @author tlwr [toby@toby.codes]
  3. * @copyright Crown Copyright 2017
  4. * @license Apache-2.0
  5. */
  6. import { fromBase64, toBase64 } from "../lib/Base64";
  7. import { fromHex } from "../lib/Hex";
  8. import Operation from "../Operation";
  9. import OperationError from "../errors/OperationError";
  10. import Utils from "../Utils";
  11. import {isImage} from "../lib/FileType";
  12. /**
  13. * Render Image operation
  14. */
  15. class RenderImage extends Operation {
  16. /**
  17. * RenderImage constructor
  18. */
  19. constructor() {
  20. super();
  21. this.name = "Render Image";
  22. this.module = "Image";
  23. this.description = "Displays the input as an image. Supports the following formats:<br><br><ul><li>jpg/jpeg</li><li>png</li><li>gif</li><li>webp</li><li>bmp</li><li>ico</li></ul>";
  24. this.inputType = "string";
  25. this.outputType = "byteArray";
  26. this.presentType = "html";
  27. this.args = [
  28. {
  29. "name": "Input format",
  30. "type": "option",
  31. "value": ["Raw", "Base64", "Hex"]
  32. }
  33. ];
  34. this.patterns = [
  35. {
  36. "match": "^(?:\\xff\\xd8\\xff|\\x89\\x50\\x4e\\x47|\\x47\\x49\\x46|.{8}\\x57\\x45\\x42\\x50|\\x42\\x4d)",
  37. "flags": "",
  38. "args": ["Raw"],
  39. "useful": true
  40. }
  41. ];
  42. }
  43. /**
  44. * @param {string} input
  45. * @param {Object[]} args
  46. * @returns {html}
  47. */
  48. run(input, args) {
  49. const inputFormat = args[0];
  50. if (!input.length) return [];
  51. // Convert input to raw bytes
  52. switch (inputFormat) {
  53. case "Hex":
  54. input = fromHex(input);
  55. break;
  56. case "Base64":
  57. // Don't trust the Base64 entered by the user.
  58. // Unwrap it first, then re-encode later.
  59. input = fromBase64(input, undefined, "byteArray");
  60. break;
  61. case "Raw":
  62. default:
  63. input = Utils.strToByteArray(input);
  64. break;
  65. }
  66. // Determine file type
  67. if (!isImage(input)) {
  68. throw new OperationError("Invalid file type");
  69. }
  70. return input;
  71. }
  72. /**
  73. * Displays the image using HTML for web apps.
  74. *
  75. * @param {byteArray} data
  76. * @returns {html}
  77. */
  78. async present(data) {
  79. if (!data.length) return "";
  80. let dataURI = "data:";
  81. // Determine file type
  82. const mime = isImage(data);
  83. if (mime) {
  84. dataURI += mime + ";";
  85. } else {
  86. throw new OperationError("Invalid file type");
  87. }
  88. // Add image data to URI
  89. dataURI += "base64," + toBase64(data);
  90. return "<img src='" + dataURI + "'>";
  91. }
  92. }
  93. export default RenderImage;