image.js 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  1. /**
  2. * @node image
  3. * @name Image
  4. * @category media
  5. * @version 1.1.0
  6. * @description Image manipulation and metadata extraction using ImageMagick
  7. * @icon image
  8. */
  9. const configSchema = {
  10. type: 'object',
  11. properties: {
  12. operation: {
  13. type: 'string',
  14. title: 'Operation',
  15. enum: ['info', 'resize', 'crop', 'rotate', 'filter', 'convert'],
  16. enumLabels: ['Info', 'Resize', 'Crop', 'Rotate', 'Filter', 'Convert Format'],
  17. default: 'info',
  18. description: 'Image operation to perform'
  19. },
  20. inputSource: {
  21. type: 'string',
  22. title: 'Input Source',
  23. enum: ['auto', 'base64', 'filePath', 'url', 'storage'],
  24. enumLabels: ['Auto-detect', 'Base64 Data', 'File Path', 'URL', 'Storage Reference'],
  25. default: 'auto',
  26. description: 'Source type for the input image'
  27. },
  28. base64Data: {
  29. type: 'string',
  30. title: 'Base64 Image Data',
  31. description: 'Base64-encoded image data. Supports {{variable}} interpolation.',
  32. showWhen: { field: 'inputSource', value: 'base64' }
  33. },
  34. filePath: {
  35. type: 'string',
  36. title: 'File Path',
  37. description: 'Path to image file on runner filesystem. Supports {{variable}} interpolation.',
  38. showWhen: { field: 'inputSource', value: 'filePath' }
  39. },
  40. url: {
  41. type: 'string',
  42. title: 'Image URL',
  43. description: 'URL to download image from. Supports {{variable}} interpolation.',
  44. showWhen: { field: 'inputSource', value: 'url' }
  45. },
  46. storageCollection: {
  47. type: 'string',
  48. title: 'Storage Collection',
  49. description: 'Collection name for stored image',
  50. showWhen: { field: 'inputSource', value: 'storage' }
  51. },
  52. storageId: {
  53. type: 'string',
  54. title: 'Storage Document ID',
  55. description: 'Document ID in storage collection. Supports {{variable}} interpolation.',
  56. showWhen: { field: 'inputSource', value: 'storage' }
  57. },
  58. includeExif: {
  59. type: 'boolean',
  60. title: 'Include EXIF Metadata',
  61. default: true,
  62. description: 'Extract EXIF metadata (camera info, GPS, date taken, etc.)',
  63. showWhen: { field: 'operation', value: 'info' }
  64. },
  65. resizeMode: {
  66. type: 'string',
  67. title: 'Resize Mode',
  68. enum: ['dimensions', 'percentage'],
  69. enumLabels: ['Dimensions (pixels)', 'Percentage (%)'],
  70. default: 'dimensions',
  71. description: 'How to specify the new size',
  72. showWhen: { field: 'operation', value: 'resize' }
  73. },
  74. resizeWidth: {
  75. type: 'number',
  76. title: 'Width',
  77. minimum: 1,
  78. maximum: 20000,
  79. description: 'Target width in pixels. Leave empty to auto-calculate from height.',
  80. showWhen: { field: 'operation', value: 'resize' }
  81. },
  82. resizeHeight: {
  83. type: 'number',
  84. title: 'Height',
  85. minimum: 1,
  86. maximum: 20000,
  87. description: 'Target height in pixels. Leave empty to auto-calculate from width.',
  88. showWhen: { field: 'operation', value: 'resize' }
  89. },
  90. resizePercentage: {
  91. type: 'number',
  92. title: 'Scale Percentage',
  93. minimum: 1,
  94. maximum: 1000,
  95. default: 100,
  96. description: 'Scale percentage (100 = original size, 50 = half, 200 = double)',
  97. showWhen: { field: 'operation', value: 'resize' }
  98. },
  99. maintainAspectRatio: {
  100. type: 'boolean',
  101. title: 'Maintain Aspect Ratio',
  102. default: true,
  103. description: 'Keep original proportions when resizing',
  104. showWhen: { field: 'operation', value: 'resize' }
  105. },
  106. cropX: {
  107. type: 'number',
  108. title: 'X Offset',
  109. minimum: 0,
  110. default: 0,
  111. description: 'Horizontal offset from left edge in pixels',
  112. showWhen: { field: 'operation', value: 'crop' }
  113. },
  114. cropY: {
  115. type: 'number',
  116. title: 'Y Offset',
  117. minimum: 0,
  118. default: 0,
  119. description: 'Vertical offset from top edge in pixels',
  120. showWhen: { field: 'operation', value: 'crop' }
  121. },
  122. cropWidth: {
  123. type: 'number',
  124. title: 'Crop Width',
  125. minimum: 1,
  126. description: 'Width of the crop region in pixels',
  127. showWhen: { field: 'operation', value: 'crop' }
  128. },
  129. cropHeight: {
  130. type: 'number',
  131. title: 'Crop Height',
  132. minimum: 1,
  133. description: 'Height of the crop region in pixels',
  134. showWhen: { field: 'operation', value: 'crop' }
  135. },
  136. rotateAngle: {
  137. type: 'number',
  138. title: 'Rotation Angle',
  139. default: 90,
  140. description: 'Rotation angle in degrees (positive = clockwise)',
  141. showWhen: { field: 'operation', value: 'rotate' }
  142. },
  143. rotatePreset: {
  144. type: 'string',
  145. title: 'Quick Rotate',
  146. enum: ['custom', '90', '180', '270'],
  147. enumLabels: ['Custom Angle', '90 (CW)', '180', '270 (CCW)'],
  148. default: 'custom',
  149. description: 'Common rotation presets or use custom angle',
  150. showWhen: { field: 'operation', value: 'rotate' }
  151. },
  152. backgroundColor: {
  153. type: 'string',
  154. title: 'Background Color',
  155. default: 'transparent',
  156. description: 'Fill color for areas exposed by rotation (name, hex, or transparent)',
  157. showWhen: { field: 'operation', value: 'rotate' }
  158. },
  159. outputFormat: {
  160. type: 'string',
  161. title: 'Output Format',
  162. enum: ['auto', 'jpeg', 'png', 'webp', 'gif'],
  163. enumLabels: ['Same as Input', 'JPEG', 'PNG', 'WebP', 'GIF'],
  164. default: 'auto',
  165. description: 'Output image format'
  166. },
  167. outputQuality: {
  168. type: 'number',
  169. title: 'Quality',
  170. minimum: 1,
  171. maximum: 100,
  172. default: 85,
  173. description: 'Output quality for lossy formats (JPEG, WebP). 1-100.'
  174. },
  175. timeout: {
  176. type: 'number',
  177. title: 'Timeout (ms)',
  178. default: 30000,
  179. minimum: 1000,
  180. maximum: 120000,
  181. description: 'Maximum time to wait for image processing'
  182. }
  183. },
  184. required: ['operation']
  185. };
  186. const inputSchema = {
  187. type: 'object',
  188. properties: {
  189. data: {
  190. type: 'any',
  191. description: 'Input data. Can be base64 string, file path, URL, or binary object from another node.'
  192. },
  193. file: {
  194. type: 'object',
  195. description: 'Binary file object with type, data (base64), mimeType, filename'
  196. },
  197. storage: {
  198. type: 'object',
  199. description: 'Storage reference with collection and id'
  200. },
  201. base64: {
  202. type: 'string',
  203. description: 'Base64-encoded image data'
  204. },
  205. filePath: {
  206. type: 'string',
  207. description: 'Override file path from input'
  208. },
  209. url: {
  210. type: 'string',
  211. description: 'Override URL from input'
  212. }
  213. }
  214. };
  215. const outputSchema = {
  216. type: 'object',
  217. properties: {
  218. width: {
  219. type: 'number',
  220. description: 'Image width in pixels'
  221. },
  222. height: {
  223. type: 'number',
  224. description: 'Image height in pixels'
  225. },
  226. format: {
  227. type: 'string',
  228. description: 'Image format (JPEG, PNG, GIF, etc.)'
  229. },
  230. colorSpace: {
  231. type: 'string',
  232. description: 'Color space (sRGB, CMYK, Grayscale, etc.)'
  233. },
  234. depth: {
  235. type: 'number',
  236. description: 'Bit depth per channel'
  237. },
  238. fileSize: {
  239. type: 'number',
  240. description: 'File size in bytes'
  241. },
  242. dpi: {
  243. type: 'object',
  244. description: 'DPI/resolution information',
  245. properties: {
  246. x: { type: 'number' },
  247. y: { type: 'number' },
  248. unit: { type: 'string' }
  249. }
  250. },
  251. hasAlpha: {
  252. type: 'boolean',
  253. description: 'Whether image has alpha/transparency channel'
  254. },
  255. compression: {
  256. type: 'string',
  257. description: 'Compression type used'
  258. },
  259. exif: {
  260. type: 'object',
  261. description: 'EXIF metadata (if available)',
  262. properties: {
  263. camera: {
  264. type: 'object',
  265. properties: {
  266. make: { type: 'string' },
  267. model: { type: 'string' },
  268. software: { type: 'string' }
  269. }
  270. },
  271. datetime: {
  272. type: 'object',
  273. properties: {
  274. original: { type: 'string' },
  275. digitized: { type: 'string' },
  276. modified: { type: 'string' }
  277. }
  278. },
  279. gps: {
  280. type: 'object',
  281. properties: {
  282. latitude: { type: 'number' },
  283. longitude: { type: 'number' },
  284. altitude: { type: 'number' },
  285. latitudeRef: { type: 'string' },
  286. longitudeRef: { type: 'string' }
  287. }
  288. },
  289. exposure: {
  290. type: 'object',
  291. properties: {
  292. time: { type: 'string' },
  293. fNumber: { type: 'number' },
  294. iso: { type: 'number' },
  295. program: { type: 'string' },
  296. bias: { type: 'string' }
  297. }
  298. },
  299. lens: {
  300. type: 'object',
  301. properties: {
  302. focalLength: { type: 'string' },
  303. focalLength35mm: { type: 'number' },
  304. aperture: { type: 'number' },
  305. make: { type: 'string' },
  306. model: { type: 'string' }
  307. }
  308. },
  309. orientation: { type: 'number' },
  310. flash: { type: 'string' },
  311. whiteBalance: { type: 'string' },
  312. meteringMode: { type: 'string' }
  313. }
  314. },
  315. file: {
  316. type: 'object',
  317. description: 'Binary file output (for manipulation operations)',
  318. properties: {
  319. type: { type: 'string', const: 'binary' },
  320. data: { type: 'string', description: 'Base64-encoded image data' },
  321. mimeType: { type: 'string', description: 'MIME type of the image' },
  322. filename: { type: 'string', description: 'Output filename' },
  323. size: { type: 'number', description: 'File size in bytes' }
  324. }
  325. },
  326. operation: {
  327. type: 'string',
  328. description: 'Operation performed'
  329. },
  330. originalWidth: {
  331. type: 'number',
  332. description: 'Original image width before manipulation'
  333. },
  334. originalHeight: {
  335. type: 'number',
  336. description: 'Original image height before manipulation'
  337. },
  338. sourceType: {
  339. type: 'string',
  340. description: 'Source type used (base64, filePath, url, storage)'
  341. },
  342. sourcePath: {
  343. type: 'string',
  344. description: 'Temporary file path used for processing'
  345. }
  346. }
  347. };
  348. function interpolate(template, data) {
  349. if (typeof template !== 'string') return template;
  350. return template.replace(/\{\{([^}]+)\}\}/g, function(match, key) {
  351. var keys = key.trim().split('.');
  352. var value = data;
  353. for (var i = 0; i < keys.length; i++) {
  354. if (value && typeof value === 'object' && keys[i] in value) {
  355. value = value[keys[i]];
  356. } else {
  357. return match;
  358. }
  359. }
  360. return value !== undefined ? String(value) : match;
  361. });
  362. }
  363. function generateTempPath(extension) {
  364. var uuid = smartbotic.utils.uuid();
  365. return '/tmp/smartbotic-image-' + uuid + (extension ? '.' + extension : '');
  366. }
  367. function detectImageFormat(base64Data) {
  368. if (!base64Data || base64Data.length < 8) return null;
  369. var header = smartbotic.utils.base64Decode(base64Data.substring(0, 16));
  370. if (!header) return null;
  371. if (header.charCodeAt(0) === 0xFF && header.charCodeAt(1) === 0xD8 && header.charCodeAt(2) === 0xFF) {
  372. return 'jpg';
  373. }
  374. if (header.substring(0, 8) === '\x89PNG\r\n\x1a\n') {
  375. return 'png';
  376. }
  377. if (header.substring(0, 6) === 'GIF87a' || header.substring(0, 6) === 'GIF89a') {
  378. return 'gif';
  379. }
  380. if (header.substring(0, 4) === 'RIFF' && header.substring(8, 12) === 'WEBP') {
  381. return 'webp';
  382. }
  383. if (header.substring(0, 2) === 'BM') {
  384. return 'bmp';
  385. }
  386. if (header.substring(0, 4) === 'II*\x00' || header.substring(0, 4) === 'MM\x00*') {
  387. return 'tiff';
  388. }
  389. return null;
  390. }
  391. function resolveImageInput(config, input) {
  392. var inputSource = config.inputSource || 'auto';
  393. var result = { type: null, data: null, path: null, tempPath: null };
  394. if (inputSource === 'filePath' || (inputSource === 'auto' && input.filePath)) {
  395. var filePath = input.filePath || interpolate(config.filePath, input);
  396. if (filePath && smartbotic.fs.exists(filePath)) {
  397. result.type = 'filePath';
  398. result.path = filePath;
  399. return result;
  400. }
  401. }
  402. if (inputSource === 'base64' || (inputSource === 'auto' && (input.base64 || config.base64Data))) {
  403. var base64 = input.base64 || interpolate(config.base64Data, input);
  404. if (base64) {
  405. result.type = 'base64';
  406. result.data = base64;
  407. return result;
  408. }
  409. }
  410. if (inputSource === 'url' || (inputSource === 'auto' && (input.url || config.url))) {
  411. var url = input.url || interpolate(config.url, input);
  412. if (url) {
  413. result.type = 'url';
  414. result.data = url;
  415. return result;
  416. }
  417. }
  418. if (inputSource === 'storage' || (inputSource === 'auto' && input.storage)) {
  419. var collection = input.storage ? input.storage.collection : config.storageCollection;
  420. var id = input.storage ? input.storage.id : interpolate(config.storageId, input);
  421. if (collection && id) {
  422. result.type = 'storage';
  423. result.data = { collection: collection, id: id };
  424. return result;
  425. }
  426. }
  427. if (inputSource === 'auto') {
  428. if (input.file && input.file.type === 'binary' && input.file.data) {
  429. result.type = 'base64';
  430. result.data = input.file.data;
  431. return result;
  432. }
  433. if (typeof input.data === 'string') {
  434. if (input.data.match(/^[A-Za-z0-9+/]+=*$/) && input.data.length > 100) {
  435. result.type = 'base64';
  436. result.data = input.data;
  437. return result;
  438. }
  439. if (input.data.startsWith('http://') || input.data.startsWith('https://')) {
  440. result.type = 'url';
  441. result.data = input.data;
  442. return result;
  443. }
  444. if (smartbotic.fs.exists(input.data)) {
  445. result.type = 'filePath';
  446. result.path = input.data;
  447. return result;
  448. }
  449. }
  450. if (input.data && typeof input.data === 'object') {
  451. if (input.data.type === 'binary' && input.data.data) {
  452. result.type = 'base64';
  453. result.data = input.data.data;
  454. return result;
  455. }
  456. if (input.data.collection && input.data.id) {
  457. result.type = 'storage';
  458. result.data = input.data;
  459. return result;
  460. }
  461. }
  462. }
  463. return result;
  464. }
  465. function prepareImageFile(imageInput, timeout) {
  466. var tempPath = null;
  467. if (imageInput.type === 'filePath') {
  468. return { path: imageInput.path, tempPath: null };
  469. }
  470. if (imageInput.type === 'base64') {
  471. var ext = detectImageFormat(imageInput.data) || 'img';
  472. tempPath = generateTempPath(ext);
  473. var writeResult = smartbotic.fs.writeFile(tempPath, imageInput.data, 'base64');
  474. if (!writeResult.success) {
  475. throw new Error('Failed to write temp file: ' + (writeResult.error || 'Unknown error'));
  476. }
  477. return { path: tempPath, tempPath: tempPath };
  478. }
  479. if (imageInput.type === 'url') {
  480. smartbotic.log.info('Downloading image from URL: ' + imageInput.data);
  481. var response = smartbotic.http.request({
  482. method: 'GET',
  483. url: imageInput.data,
  484. timeout: timeout
  485. });
  486. if (response.status < 200 || response.status >= 300) {
  487. throw new Error('Failed to download image: HTTP ' + response.status);
  488. }
  489. var contentType = response.headers['content-type'] || '';
  490. var ext = 'img';
  491. if (contentType.includes('jpeg') || contentType.includes('jpg')) ext = 'jpg';
  492. else if (contentType.includes('png')) ext = 'png';
  493. else if (contentType.includes('gif')) ext = 'gif';
  494. else if (contentType.includes('webp')) ext = 'webp';
  495. tempPath = generateTempPath(ext);
  496. var base64Data = smartbotic.utils.base64Encode(response.data);
  497. var writeResult = smartbotic.fs.writeFile(tempPath, base64Data, 'base64');
  498. if (!writeResult.success) {
  499. throw new Error('Failed to write downloaded image: ' + (writeResult.error || 'Unknown error'));
  500. }
  501. return { path: tempPath, tempPath: tempPath };
  502. }
  503. if (imageInput.type === 'storage') {
  504. var storageResult = smartbotic.storage.get(imageInput.data.collection, imageInput.data.id);
  505. if (!storageResult.found) {
  506. throw new Error('Image not found in storage: ' + imageInput.data.collection + '/' + imageInput.data.id);
  507. }
  508. var doc = storageResult.document;
  509. var base64Data = doc.data || doc.content || doc.base64;
  510. if (!base64Data) {
  511. throw new Error('Storage document does not contain image data');
  512. }
  513. var ext = detectImageFormat(base64Data) || 'img';
  514. tempPath = generateTempPath(ext);
  515. var writeResult = smartbotic.fs.writeFile(tempPath, base64Data, 'base64');
  516. if (!writeResult.success) {
  517. throw new Error('Failed to write storage image: ' + (writeResult.error || 'Unknown error'));
  518. }
  519. return { path: tempPath, tempPath: tempPath };
  520. }
  521. throw new Error('No valid image input found');
  522. }
  523. function cleanupTempFile(tempPath) {
  524. if (tempPath) {
  525. try {
  526. smartbotic.fs.unlink(tempPath);
  527. } catch (e) {
  528. smartbotic.log.warn('Failed to cleanup temp file: ' + tempPath);
  529. }
  530. }
  531. }
  532. function parseImageMagickInfo(output) {
  533. var info = {};
  534. var lines = output.split('\n');
  535. for (var i = 0; i < lines.length; i++) {
  536. var line = lines[i].trim();
  537. if (!line) continue;
  538. var colonIdx = line.indexOf(':');
  539. if (colonIdx > 0) {
  540. var key = line.substring(0, colonIdx).trim().toLowerCase();
  541. var value = line.substring(colonIdx + 1).trim();
  542. if (key === 'image' || key === 'format') {
  543. var formatMatch = value.match(/^(\w+)/);
  544. if (formatMatch) info.format = formatMatch[1].toUpperCase();
  545. }
  546. else if (key === 'geometry' || key === 'page geometry') {
  547. var geomMatch = value.match(/(\d+)x(\d+)/);
  548. if (geomMatch) {
  549. info.width = parseInt(geomMatch[1], 10);
  550. info.height = parseInt(geomMatch[2], 10);
  551. }
  552. }
  553. else if (key === 'colorspace') {
  554. info.colorSpace = value;
  555. }
  556. else if (key === 'depth') {
  557. var depthMatch = value.match(/(\d+)/);
  558. if (depthMatch) info.depth = parseInt(depthMatch[1], 10);
  559. }
  560. else if (key === 'channel depth' || key === 'channels') {
  561. if (value.toLowerCase().includes('alpha')) {
  562. info.hasAlpha = true;
  563. }
  564. }
  565. else if (key === 'alpha') {
  566. info.hasAlpha = value.toLowerCase() !== 'undefined' && value.toLowerCase() !== 'off';
  567. }
  568. else if (key === 'compression') {
  569. info.compression = value;
  570. }
  571. else if (key === 'resolution' || key === 'units') {
  572. if (!info.dpi) info.dpi = {};
  573. var resMatch = value.match(/([\d.]+)x([\d.]+)/);
  574. if (resMatch) {
  575. info.dpi.x = parseFloat(resMatch[1]);
  576. info.dpi.y = parseFloat(resMatch[2]);
  577. }
  578. if (value.includes('PixelsPerInch')) info.dpi.unit = 'dpi';
  579. else if (value.includes('PixelsPerCentimeter')) info.dpi.unit = 'dpcm';
  580. }
  581. else if (key === 'filesize') {
  582. var sizeMatch = value.match(/([\d.]+)\s*(\w+)/);
  583. if (sizeMatch) {
  584. var size = parseFloat(sizeMatch[1]);
  585. var unit = sizeMatch[2].toUpperCase();
  586. if (unit === 'B') info.fileSize = Math.round(size);
  587. else if (unit === 'KB' || unit === 'KIB') info.fileSize = Math.round(size * 1024);
  588. else if (unit === 'MB' || unit === 'MIB') info.fileSize = Math.round(size * 1024 * 1024);
  589. else if (unit === 'GB' || unit === 'GIB') info.fileSize = Math.round(size * 1024 * 1024 * 1024);
  590. }
  591. }
  592. }
  593. }
  594. if (info.hasAlpha === undefined) info.hasAlpha = false;
  595. return info;
  596. }
  597. function parseExifToolOutput(output) {
  598. var exif = {
  599. camera: {},
  600. datetime: {},
  601. gps: {},
  602. exposure: {},
  603. lens: {}
  604. };
  605. var lines = output.split('\n');
  606. for (var i = 0; i < lines.length; i++) {
  607. var line = lines[i].trim();
  608. if (!line) continue;
  609. var colonIdx = line.indexOf(':');
  610. if (colonIdx <= 0) continue;
  611. var key = line.substring(0, colonIdx).trim().toLowerCase().replace(/\s+/g, '');
  612. var value = line.substring(colonIdx + 1).trim();
  613. if (!value || value === '-' || value === 'n/a') continue;
  614. if (key === 'make' || key === 'cameramake') exif.camera.make = value;
  615. else if (key === 'model' || key === 'cameramodel' || key === 'cameramodelname') exif.camera.model = value;
  616. else if (key === 'software') exif.camera.software = value;
  617. else if (key === 'datetimeoriginal' || key === 'createdate') exif.datetime.original = value;
  618. else if (key === 'datetimedigitized' || key === 'digitizeddate') exif.datetime.digitized = value;
  619. else if (key === 'modifydate' || key === 'datetime') exif.datetime.modified = value;
  620. else if (key === 'gpslatitude') {
  621. var latMatch = value.match(/([\d.]+)/);
  622. if (latMatch) {
  623. exif.gps.latitude = parseFloat(latMatch[1]);
  624. if (value.includes('S')) exif.gps.latitude = -exif.gps.latitude;
  625. exif.gps.latitudeRef = value.includes('S') ? 'S' : 'N';
  626. }
  627. }
  628. else if (key === 'gpslongitude') {
  629. var lonMatch = value.match(/([\d.]+)/);
  630. if (lonMatch) {
  631. exif.gps.longitude = parseFloat(lonMatch[1]);
  632. if (value.includes('W')) exif.gps.longitude = -exif.gps.longitude;
  633. exif.gps.longitudeRef = value.includes('W') ? 'W' : 'E';
  634. }
  635. }
  636. else if (key === 'gpsaltitude') {
  637. var altMatch = value.match(/([\d.]+)/);
  638. if (altMatch) exif.gps.altitude = parseFloat(altMatch[1]);
  639. }
  640. else if (key === 'exposuretime' || key === 'shutterspeed') exif.exposure.time = value;
  641. else if (key === 'fnumber' || key === 'aperture') {
  642. var fMatch = value.match(/([\d.]+)/);
  643. if (fMatch) exif.exposure.fNumber = parseFloat(fMatch[1]);
  644. }
  645. else if (key === 'iso' || key === 'isospeedratings') {
  646. var isoMatch = value.match(/(\d+)/);
  647. if (isoMatch) exif.exposure.iso = parseInt(isoMatch[1], 10);
  648. }
  649. else if (key === 'exposureprogram') exif.exposure.program = value;
  650. else if (key === 'exposurecompensation' || key === 'exposurebias') exif.exposure.bias = value;
  651. else if (key === 'focallength') exif.lens.focalLength = value;
  652. else if (key === 'focallengthin35mmformat' || key === 'focallength35efl') {
  653. var fl35Match = value.match(/(\d+)/);
  654. if (fl35Match) exif.lens.focalLength35mm = parseInt(fl35Match[1], 10);
  655. }
  656. else if (key === 'maxaperturevalue') {
  657. var apMatch = value.match(/([\d.]+)/);
  658. if (apMatch) exif.lens.aperture = parseFloat(apMatch[1]);
  659. }
  660. else if (key === 'lensmake') exif.lens.make = value;
  661. else if (key === 'lensmodel' || key === 'lens') exif.lens.model = value;
  662. else if (key === 'orientation') {
  663. var oriMatch = value.match(/(\d)/);
  664. if (oriMatch) exif.orientation = parseInt(oriMatch[1], 10);
  665. }
  666. else if (key === 'flash') exif.flash = value;
  667. else if (key === 'whitebalance') exif.whiteBalance = value;
  668. else if (key === 'meteringmode') exif.meteringMode = value;
  669. }
  670. var hasData = false;
  671. for (var section in exif) {
  672. if (typeof exif[section] === 'object') {
  673. for (var field in exif[section]) {
  674. if (exif[section][field] !== undefined) {
  675. hasData = true;
  676. break;
  677. }
  678. }
  679. } else if (exif[section] !== undefined) {
  680. hasData = true;
  681. }
  682. if (hasData) break;
  683. }
  684. return hasData ? exif : null;
  685. }
  686. function executeInfoOperation(imagePath, includeExif, timeout) {
  687. smartbotic.log.info('Running ImageMagick identify on: ' + imagePath);
  688. var identifyCmd = 'identify -verbose "' + imagePath.replace(/"/g, '\\"') + '"';
  689. var identifyResult = smartbotic.process.exec(identifyCmd, { timeout: timeout });
  690. if (!identifyResult.success) {
  691. throw new Error('ImageMagick identify failed: ' + (identifyResult.stderr || 'Unknown error'));
  692. }
  693. var info = parseImageMagickInfo(identifyResult.stdout);
  694. var stat = smartbotic.fs.stat(imagePath);
  695. if (stat.success && !info.fileSize) {
  696. info.fileSize = stat.size;
  697. }
  698. if (includeExif) {
  699. smartbotic.log.info('Extracting EXIF metadata');
  700. var exiftoolCmd = 'exiftool "' + imagePath.replace(/"/g, '\\"') + '"';
  701. var exifResult = smartbotic.process.exec(exiftoolCmd, { timeout: timeout });
  702. if (exifResult.success && exifResult.stdout) {
  703. var exifData = parseExifToolOutput(exifResult.stdout);
  704. if (exifData) {
  705. info.exif = exifData;
  706. }
  707. } else {
  708. smartbotic.log.debug('No EXIF data available or exiftool not installed');
  709. }
  710. }
  711. return info;
  712. }
  713. function getImageDimensions(imagePath, timeout) {
  714. var cmd = 'identify -format "%w %h" "' + imagePath.replace(/"/g, '\\"') + '"';
  715. var result = smartbotic.process.exec(cmd, { timeout: timeout });
  716. if (!result.success) {
  717. throw new Error('Failed to get image dimensions: ' + (result.stderr || 'Unknown error'));
  718. }
  719. var parts = result.stdout.trim().split(' ');
  720. return {
  721. width: parseInt(parts[0], 10),
  722. height: parseInt(parts[1], 10)
  723. };
  724. }
  725. function getOutputExtension(format, originalPath) {
  726. if (format === 'auto') {
  727. var ext = originalPath.split('.').pop().toLowerCase();
  728. if (['jpg', 'jpeg', 'png', 'gif', 'webp'].indexOf(ext) >= 0) {
  729. return ext === 'jpg' ? 'jpeg' : ext;
  730. }
  731. return 'jpeg';
  732. }
  733. return format;
  734. }
  735. function getMimeType(format) {
  736. var mimeTypes = {
  737. jpeg: 'image/jpeg',
  738. jpg: 'image/jpeg',
  739. png: 'image/png',
  740. gif: 'image/gif',
  741. webp: 'image/webp'
  742. };
  743. return mimeTypes[format] || 'image/jpeg';
  744. }
  745. function buildOutputPath(format) {
  746. var uuid = smartbotic.utils.uuid();
  747. return '/tmp/smartbotic-image-out-' + uuid + '.' + format;
  748. }
  749. function readOutputFile(outputPath) {
  750. var readResult = smartbotic.fs.readFile(outputPath, 'base64');
  751. if (!readResult.success) {
  752. throw new Error('Failed to read output file: ' + (readResult.error || 'Unknown error'));
  753. }
  754. return readResult.data;
  755. }
  756. function getOutputFileSize(outputPath) {
  757. var stat = smartbotic.fs.stat(outputPath);
  758. return stat.success ? stat.size : 0;
  759. }
  760. function cleanupOutputFile(outputPath) {
  761. if (outputPath) {
  762. try {
  763. smartbotic.fs.unlink(outputPath);
  764. } catch (e) {
  765. smartbotic.log.warn('Failed to cleanup output file: ' + outputPath);
  766. }
  767. }
  768. }
  769. function buildQualityArgs(format, quality) {
  770. if (format === 'jpeg' || format === 'webp') {
  771. return ' -quality ' + quality;
  772. }
  773. if (format === 'png') {
  774. var pngQuality = Math.round((100 - quality) / 10);
  775. return ' -quality ' + (pngQuality * 10);
  776. }
  777. return '';
  778. }
  779. function executeResizeOperation(imagePath, config, timeout) {
  780. var dimensions = getImageDimensions(imagePath, timeout);
  781. var originalWidth = dimensions.width;
  782. var originalHeight = dimensions.height;
  783. var resizeMode = config.resizeMode || 'dimensions';
  784. var maintainAspectRatio = config.maintainAspectRatio !== false;
  785. var targetWidth, targetHeight;
  786. if (resizeMode === 'percentage') {
  787. var percentage = config.resizePercentage || 100;
  788. targetWidth = Math.round(originalWidth * percentage / 100);
  789. targetHeight = Math.round(originalHeight * percentage / 100);
  790. smartbotic.log.info('Resizing by ' + percentage + '% to ' + targetWidth + 'x' + targetHeight);
  791. } else {
  792. targetWidth = config.resizeWidth;
  793. targetHeight = config.resizeHeight;
  794. if (!targetWidth && !targetHeight) {
  795. throw new Error('Resize operation requires at least width or height');
  796. }
  797. if (maintainAspectRatio) {
  798. if (targetWidth && !targetHeight) {
  799. targetHeight = Math.round(originalHeight * targetWidth / originalWidth);
  800. } else if (targetHeight && !targetWidth) {
  801. targetWidth = Math.round(originalWidth * targetHeight / originalHeight);
  802. }
  803. } else {
  804. targetWidth = targetWidth || originalWidth;
  805. targetHeight = targetHeight || originalHeight;
  806. }
  807. smartbotic.log.info('Resizing to ' + targetWidth + 'x' + targetHeight + ' (aspect ratio ' + (maintainAspectRatio ? 'maintained' : 'ignored') + ')');
  808. }
  809. var outputFormat = getOutputExtension(config.outputFormat || 'auto', imagePath);
  810. var quality = config.outputQuality || 85;
  811. var outputPath = buildOutputPath(outputFormat);
  812. var resizeSpec = targetWidth + 'x' + targetHeight;
  813. if (!maintainAspectRatio && resizeMode === 'dimensions') {
  814. resizeSpec += '!';
  815. }
  816. var cmd = 'convert "' + imagePath.replace(/"/g, '\\"') + '"';
  817. cmd += ' -resize ' + resizeSpec;
  818. cmd += buildQualityArgs(outputFormat, quality);
  819. cmd += ' "' + outputPath.replace(/"/g, '\\"') + '"';
  820. smartbotic.log.info('Executing: ' + cmd);
  821. var result = smartbotic.process.exec(cmd, { timeout: timeout });
  822. if (!result.success) {
  823. cleanupOutputFile(outputPath);
  824. throw new Error('Resize operation failed: ' + (result.stderr || 'Unknown error'));
  825. }
  826. var base64Data = readOutputFile(outputPath);
  827. var fileSize = getOutputFileSize(outputPath);
  828. cleanupOutputFile(outputPath);
  829. return {
  830. operation: 'resize',
  831. originalWidth: originalWidth,
  832. originalHeight: originalHeight,
  833. width: targetWidth,
  834. height: targetHeight,
  835. format: outputFormat.toUpperCase(),
  836. file: {
  837. type: 'binary',
  838. data: base64Data,
  839. mimeType: getMimeType(outputFormat),
  840. filename: 'resized.' + outputFormat,
  841. size: fileSize
  842. }
  843. };
  844. }
  845. function executeCropOperation(imagePath, config, timeout) {
  846. var dimensions = getImageDimensions(imagePath, timeout);
  847. var originalWidth = dimensions.width;
  848. var originalHeight = dimensions.height;
  849. var cropX = config.cropX || 0;
  850. var cropY = config.cropY || 0;
  851. var cropWidth = config.cropWidth;
  852. var cropHeight = config.cropHeight;
  853. if (!cropWidth || !cropHeight) {
  854. throw new Error('Crop operation requires both width and height');
  855. }
  856. if (cropX < 0 || cropY < 0) {
  857. throw new Error('Crop offset cannot be negative');
  858. }
  859. if (cropX + cropWidth > originalWidth || cropY + cropHeight > originalHeight) {
  860. throw new Error('Crop region exceeds image bounds. Image is ' + originalWidth + 'x' + originalHeight + ', crop would extend to ' + (cropX + cropWidth) + 'x' + (cropY + cropHeight));
  861. }
  862. smartbotic.log.info('Cropping ' + cropWidth + 'x' + cropHeight + ' from offset ' + cropX + ',' + cropY);
  863. var outputFormat = getOutputExtension(config.outputFormat || 'auto', imagePath);
  864. var quality = config.outputQuality || 85;
  865. var outputPath = buildOutputPath(outputFormat);
  866. var cmd = 'convert "' + imagePath.replace(/"/g, '\\"') + '"';
  867. cmd += ' -crop ' + cropWidth + 'x' + cropHeight + '+' + cropX + '+' + cropY;
  868. cmd += ' +repage';
  869. cmd += buildQualityArgs(outputFormat, quality);
  870. cmd += ' "' + outputPath.replace(/"/g, '\\"') + '"';
  871. smartbotic.log.info('Executing: ' + cmd);
  872. var result = smartbotic.process.exec(cmd, { timeout: timeout });
  873. if (!result.success) {
  874. cleanupOutputFile(outputPath);
  875. throw new Error('Crop operation failed: ' + (result.stderr || 'Unknown error'));
  876. }
  877. var base64Data = readOutputFile(outputPath);
  878. var fileSize = getOutputFileSize(outputPath);
  879. cleanupOutputFile(outputPath);
  880. return {
  881. operation: 'crop',
  882. originalWidth: originalWidth,
  883. originalHeight: originalHeight,
  884. width: cropWidth,
  885. height: cropHeight,
  886. cropRegion: {
  887. x: cropX,
  888. y: cropY,
  889. width: cropWidth,
  890. height: cropHeight
  891. },
  892. format: outputFormat.toUpperCase(),
  893. file: {
  894. type: 'binary',
  895. data: base64Data,
  896. mimeType: getMimeType(outputFormat),
  897. filename: 'cropped.' + outputFormat,
  898. size: fileSize
  899. }
  900. };
  901. }
  902. function executeRotateOperation(imagePath, config, timeout) {
  903. var dimensions = getImageDimensions(imagePath, timeout);
  904. var originalWidth = dimensions.width;
  905. var originalHeight = dimensions.height;
  906. var rotatePreset = config.rotatePreset || 'custom';
  907. var angle;
  908. if (rotatePreset === 'custom') {
  909. angle = config.rotateAngle;
  910. if (angle === undefined || angle === null) {
  911. angle = 90;
  912. }
  913. } else {
  914. angle = parseInt(rotatePreset, 10);
  915. }
  916. angle = angle % 360;
  917. if (angle < 0) {
  918. angle += 360;
  919. }
  920. var backgroundColor = config.backgroundColor || 'transparent';
  921. smartbotic.log.info('Rotating ' + angle + ' degrees with background: ' + backgroundColor);
  922. var outputFormat = getOutputExtension(config.outputFormat || 'auto', imagePath);
  923. var quality = config.outputQuality || 85;
  924. var outputPath = buildOutputPath(outputFormat);
  925. var supportsTransparency = (outputFormat === 'png' || outputFormat === 'gif' || outputFormat === 'webp');
  926. var cmd = 'convert "' + imagePath.replace(/"/g, '\\"') + '"';
  927. if (backgroundColor === 'transparent' && supportsTransparency) {
  928. cmd += ' -background none';
  929. } else if (backgroundColor === 'transparent') {
  930. cmd += ' -background white';
  931. } else {
  932. cmd += ' -background "' + backgroundColor.replace(/"/g, '\\"') + '"';
  933. }
  934. cmd += ' -rotate ' + angle;
  935. cmd += buildQualityArgs(outputFormat, quality);
  936. cmd += ' "' + outputPath.replace(/"/g, '\\"') + '"';
  937. smartbotic.log.info('Executing: ' + cmd);
  938. var result = smartbotic.process.exec(cmd, { timeout: timeout });
  939. if (!result.success) {
  940. cleanupOutputFile(outputPath);
  941. throw new Error('Rotate operation failed: ' + (result.stderr || 'Unknown error'));
  942. }
  943. var newDimensions = getImageDimensions(outputPath, timeout);
  944. var base64Data = readOutputFile(outputPath);
  945. var fileSize = getOutputFileSize(outputPath);
  946. cleanupOutputFile(outputPath);
  947. return {
  948. operation: 'rotate',
  949. originalWidth: originalWidth,
  950. originalHeight: originalHeight,
  951. width: newDimensions.width,
  952. height: newDimensions.height,
  953. angle: angle,
  954. backgroundColor: backgroundColor,
  955. format: outputFormat.toUpperCase(),
  956. file: {
  957. type: 'binary',
  958. data: base64Data,
  959. mimeType: getMimeType(outputFormat),
  960. filename: 'rotated.' + outputFormat,
  961. size: fileSize
  962. }
  963. };
  964. }
  965. async function execute(config, input) {
  966. var operation = config.operation || 'info';
  967. var timeout = config.timeout || 30000;
  968. var supportedOperations = ['info', 'resize', 'crop', 'rotate'];
  969. if (supportedOperations.indexOf(operation) < 0) {
  970. throw new Error('Operation "' + operation + '" is not yet implemented. Supported: ' + supportedOperations.join(', '));
  971. }
  972. var imageInput = resolveImageInput(config, input);
  973. if (!imageInput.type) {
  974. throw new Error('No valid image input found. Provide base64 data, file path, URL, or storage reference.');
  975. }
  976. smartbotic.log.info('Image input source: ' + imageInput.type);
  977. var fileInfo = null;
  978. try {
  979. fileInfo = prepareImageFile(imageInput, timeout);
  980. smartbotic.log.info('Processing image: ' + fileInfo.path);
  981. var result;
  982. if (operation === 'info') {
  983. result = executeInfoOperation(fileInfo.path, config.includeExif !== false, timeout);
  984. } else if (operation === 'resize') {
  985. result = executeResizeOperation(fileInfo.path, config, timeout);
  986. } else if (operation === 'crop') {
  987. result = executeCropOperation(fileInfo.path, config, timeout);
  988. } else if (operation === 'rotate') {
  989. result = executeRotateOperation(fileInfo.path, config, timeout);
  990. }
  991. result.sourceType = imageInput.type;
  992. result.sourcePath = fileInfo.path;
  993. return result;
  994. } finally {
  995. if (fileInfo && fileInfo.tempPath) {
  996. cleanupTempFile(fileInfo.tempPath);
  997. }
  998. }
  999. }
  1000. module.exports = { configSchema, inputSchema, outputSchema, execute };