Merge pull request #56 from SELab-2/feat/base64-image
feat: base64ToImage.ts
This commit is contained in:
commit
8a7fa271ba
3 changed files with 45 additions and 0 deletions
20
frontend/src/utils/base64ToImage.ts
Normal file
20
frontend/src/utils/base64ToImage.ts
Normal file
|
@ -0,0 +1,20 @@
|
|||
/**
|
||||
* Converts a Base64 string to a valid image source URL.
|
||||
*
|
||||
* @param base64String - The "image" field from the learning path JSON response.
|
||||
* @returns A properly formatted data URL for use in an <img> tag.
|
||||
*
|
||||
* @example
|
||||
* // Fetch the learning path data and extract the image
|
||||
* const response = await fetch( learning path route );
|
||||
* const data = await response.json();
|
||||
* const base64String = data.image;
|
||||
*
|
||||
* // Use in an <img> element
|
||||
* <img :src="convertBase64ToImageSrc(base64String)" alt="Learning Path Image" />
|
||||
*/
|
||||
export function convertBase64ToImageSrc(base64String: string): string {
|
||||
return base64String.startsWith("data:image")
|
||||
? base64String
|
||||
: `data:image/png;base64,${base64String}`;
|
||||
}
|
1
frontend/tests/base64/base64Sample.txt
Normal file
1
frontend/tests/base64/base64Sample.txt
Normal file
File diff suppressed because one or more lines are too long
24
frontend/tests/base64/base64ToImage.test.ts
Normal file
24
frontend/tests/base64/base64ToImage.test.ts
Normal file
|
@ -0,0 +1,24 @@
|
|||
import { describe, it, expect, beforeAll } from 'vitest';
|
||||
import { convertBase64ToImageSrc } from '../../src/utils/base64ToImage.js';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
let sampleBase64: string;
|
||||
|
||||
beforeAll(() => {
|
||||
// Load base64 sample from text file
|
||||
const filePath = path.resolve(__dirname, 'base64Sample.txt');
|
||||
sampleBase64 = fs.readFileSync(filePath, 'utf8').trim();
|
||||
});
|
||||
|
||||
describe('convertBase64ToImageSrc', () => {
|
||||
it('should return the same string if it is already a valid data URL', () => {
|
||||
const base64Image = `data:image/png;base64,${sampleBase64}`;
|
||||
expect(convertBase64ToImageSrc(base64Image)).toBe(base64Image);
|
||||
});
|
||||
|
||||
it('should correctly format a raw Base64 string as a PNG image URL', () => {
|
||||
expect(convertBase64ToImageSrc(sampleBase64)).toBe(`data:image/png;base64,${sampleBase64}`);
|
||||
});
|
||||
|
||||
});
|
Loading…
Add table
Add a link
Reference in a new issue