DigitalDB / frontend /src /utils /imageUtils.js
Mr-Thop's picture
Add files
3db086d
Raw
History Blame Contribute Delete
2.37 kB
// Utility functions for handling image URLs
/**
* Convert Google Drive share URL to local image path
* @param {string} url - Google Drive share URL
* @param {number} mediaId - Media ID from database
* @param {string} plantName - Plant name for fallback
* @returns {string} - Local image path or fallback
*/
export const convertGoogleDriveUrl = (url, mediaId, plantName) => {
if (!url) return null;
// If we have media ID, try to use local downloaded image
if (mediaId) {
// Create filename similar to Python script
const safePlantName = plantName
? plantName.replace(/[^\w\s-]/g, '').trim().replace(/[-\s]+/g, '_')
: 'unknown';
const localPath = `/images/${mediaId}_${safePlantName}.jpg`;
return localPath;
}
// Fallback to original URL processing (shouldn't happen now)
if (url.includes('drive.google.com')) {
const viewMatch = url.match(/\/file\/d\/([a-zA-Z0-9-_]+)/);
if (viewMatch) {
const fileId = viewMatch[1];
return `https://drive.google.com/uc?export=view&id=${fileId}`;
}
}
return url;
};
/**
* Get image URL with fallback - updated for local images
* @param {string} url - Original image URL
* @param {number} mediaId - Media ID from database
* @param {string} plantName - Plant name
* @returns {string} - Processed image URL
*/
export const getImageUrl = (url, mediaId, plantName) => {
if (!url) return null;
return convertGoogleDriveUrl(url, mediaId, plantName);
};
/**
* Create a placeholder image URL
* @param {number} width - Image width
* @param {number} height - Image height
* @param {string} text - Text to display
* @returns {string} - Data URL for placeholder image
*/
export const getPlaceholderImage = (width = 300, height = 200, text = 'No Image') => {
return `data:image/svg+xml;base64,${btoa(`
<svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="${width}" height="${height}" fill="#f3f4f6"/>
<rect x="20" y="20" width="${width-40}" height="${height-40}" rx="8" fill="#e5e7eb"/>
<text x="${width/2}" y="${height/2}" font-family="Arial, sans-serif" font-size="16" text-anchor="middle" dominant-baseline="central" fill="#6b7280">${text}</text>
</svg>
`)}`;
};