RenderImage.mjs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 Utils from "../Utils";
  10. import Magic from "../lib/Magic";
  11. /**
  12. * Render Image operation
  13. */
  14. class RenderImage extends Operation {
  15. /**
  16. * RenderImage constructor
  17. */
  18. constructor() {
  19. super();
  20. this.name = "Render Image";
  21. this.module = "Image";
  22. 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>";
  23. this.inputType = "string";
  24. this.outputType = "html";
  25. this.args = [
  26. {
  27. "name": "Input format",
  28. "type": "option",
  29. "value": ["Raw", "Base64", "Hex"]
  30. }
  31. ];
  32. this.patterns = [
  33. {
  34. "match": "^(?:\\xff\\xd8\\xff|\\x89\\x50\\x4e\\x47|\\x47\\x49\\x46|.{8}\\x57\\x45\\x42\\x50|\\x42\\x4d)",
  35. "flags": "",
  36. "args": [
  37. "Raw"
  38. ],
  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. let dataURI = "data:";
  51. if (!input.length) return "";
  52. // Convert input to raw bytes
  53. switch (inputFormat) {
  54. case "Hex":
  55. input = fromHex(input);
  56. break;
  57. case "Base64":
  58. // Don't trust the Base64 entered by the user.
  59. // Unwrap it first, then re-encode later.
  60. input = fromBase64(input, undefined, "byteArray");
  61. break;
  62. case "Raw":
  63. default:
  64. input = Utils.strToByteArray(input);
  65. break;
  66. }
  67. // Determine file type
  68. const type = Magic.magicFileType(input);
  69. if (type && type.mime.indexOf("image") === 0) {
  70. dataURI += type.mime + ";";
  71. } else {
  72. throw "Invalid file type";
  73. }
  74. // Add image data to URI
  75. dataURI += "base64," + toBase64(input);
  76. return "<img src='" + dataURI + "'>";
  77. }
  78. }
  79. export default RenderImage;