2018-05-27 23:27:11 +01:00
/**
* @author tlwr [toby@toby.codes]
* @copyright Crown Copyright 2017
* @license Apache-2.0
*/
2019-07-09 12:23:59 +01:00
import { fromBase64 , toBase64 } from "../lib/Base64.mjs" ;
import { fromHex } from "../lib/Hex.mjs" ;
import Operation from "../Operation.mjs" ;
import OperationError from "../errors/OperationError.mjs" ;
import Utils from "../Utils.mjs" ;
import { isImage } from "../lib/FileType.mjs" ;
2018-05-27 23:27:11 +01:00
/**
* Render Image operation
*/
class RenderImage extends Operation {
/**
* RenderImage constructor
*/
constructor () {
super ();
this . name = "Render Image" ;
this . module = "Image" ;
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>" ;
this . inputType = "string" ;
2018-08-09 19:17:24 +01:00
this . outputType = "byteArray" ;
this . presentType = "html" ;
2018-05-27 23:27:11 +01:00
this . args = [
{
"name" : "Input format" ,
"type" : "option" ,
"value" : [ "Raw" , "Base64" , "Hex" ]
}
];
2020-03-24 11:06:37 +00:00
this . checks = [
{
pattern : "^(?:\\xff\\xd8\\xff|\\x89\\x50\\x4e\\x47|\\x47\\x49\\x46|.{8}\\x57\\x45\\x42\\x50|\\x42\\x4d)" ,
flags : "" ,
args : [ "Raw" ],
useful : true ,
output : {
mime : "image"
}
2018-05-27 23:27:11 +01:00
}
2020-03-24 11:06:37 +00:00
];
2018-05-27 23:27:11 +01:00
}
/**
* @param {string} input
* @param {Object[]} args
* @returns {html}
*/
run ( input , args ) {
const inputFormat = args [ 0 ];
2018-08-09 19:17:24 +01:00
if ( ! input . length ) return [];
2018-05-27 23:27:11 +01:00
// Convert input to raw bytes
switch ( inputFormat ) {
case "Hex" :
input = fromHex ( input );
break ;
case "Base64" :
// Don't trust the Base64 entered by the user.
// Unwrap it first, then re-encode later.
input = fromBase64 ( input , undefined , "byteArray" );
break ;
case "Raw" :
default :
input = Utils . strToByteArray ( input );
break ;
}
// Determine file type
2018-12-26 18:40:27 +00:00
if ( ! isImage ( input )) {
2018-08-09 19:17:24 +01:00
throw new OperationError ( "Invalid file type" );
}
return input ;
}
/**
* Displays the image using HTML for web apps.
*
* @param {byteArray} data
* @returns {html}
*/
async present ( data ) {
if ( ! data . length ) return "" ;
let dataURI = "data:" ;
// Determine file type
2018-12-26 18:40:27 +00:00
const mime = isImage ( data );
if ( mime ) {
dataURI += mime + ";" ;
2018-05-27 23:27:11 +01:00
} else {
2018-05-28 15:42:43 -07:00
throw new OperationError ( "Invalid file type" );
2018-05-27 23:27:11 +01:00
}
// Add image data to URI
2018-08-09 19:17:24 +01:00
dataURI += "base64," + toBase64 ( data );
2018-05-27 23:27:11 +01:00
return "<img src='" + dataURI + "'>" ;
}
}
export default RenderImage ;