imageViewer.ts•2.91 kB
import * as fs from 'fs';
import * as path from 'path';
export interface ImageInfo {
path: string;
name: string;
size: number;
mimeType: string;
base64Data: string;
}
const SUPPORTED_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg'];
export function getMimeType(filePath: string): string {
const ext = path.extname(filePath).toLowerCase();
switch (ext) {
case '.jpg':
case '.jpeg':
return 'image/jpeg';
case '.png':
return 'image/png';
case '.gif':
return 'image/gif';
case '.bmp':
return 'image/bmp';
case '.webp':
return 'image/webp';
case '.svg':
return 'image/svg+xml';
default:
return 'application/octet-stream';
}
}
export function isImageFile(filePath: string): boolean {
const ext = path.extname(filePath).toLowerCase();
return SUPPORTED_EXTENSIONS.includes(ext);
}
export async function loadImage(imagePath: string): Promise<ImageInfo> {
// Resolve the path to handle ~ and relative paths
const resolvedPath = path.resolve(imagePath.replace(/^~/, process.env.HOME || ''));
if (!fs.existsSync(resolvedPath)) {
throw new Error(`Image file not found: ${resolvedPath}`);
}
if (!isImageFile(resolvedPath)) {
throw new Error(`File is not a supported image type: ${resolvedPath}`);
}
const stats = fs.statSync(resolvedPath);
const imageData = fs.readFileSync(resolvedPath);
const base64Data = imageData.toString('base64');
return {
path: resolvedPath,
name: path.basename(resolvedPath),
size: stats.size,
mimeType: getMimeType(resolvedPath),
base64Data: base64Data
};
}
export async function findImages(searchPath: string, recursive: boolean = false): Promise<string[]> {
const resolvedPath = path.resolve(searchPath.replace(/^~/, process.env.HOME || ''));
if (!fs.existsSync(resolvedPath)) {
throw new Error(`Directory not found: ${resolvedPath}`);
}
const results: string[] = [];
function scanDirectory(dirPath: string) {
const items = fs.readdirSync(dirPath);
for (const item of items) {
const itemPath = path.join(dirPath, item);
const stats = fs.statSync(itemPath);
if (stats.isFile() && isImageFile(itemPath)) {
results.push(itemPath);
} else if (stats.isDirectory() && recursive) {
scanDirectory(itemPath);
}
}
}
const stats = fs.statSync(resolvedPath);
if (stats.isFile()) {
if (isImageFile(resolvedPath)) {
results.push(resolvedPath);
}
} else if (stats.isDirectory()) {
scanDirectory(resolvedPath);
}
return results.sort();
}