Cropping mostly done
This commit is contained in:
@@ -126,3 +126,80 @@ export async function getSheetData(spreadsheetId: string, range: string) {
|
||||
});
|
||||
return response.result.values || [];
|
||||
}
|
||||
|
||||
// Extract Google Drive file ID from various URL formats
|
||||
export function extractDriveFileId(url: string): string | null {
|
||||
if (!url) return null;
|
||||
|
||||
// Handle different Google Drive URL formats
|
||||
const patterns = [
|
||||
/\/file\/d\/([a-zA-Z0-9-_]+)/, // https://drive.google.com/file/d/FILE_ID/view
|
||||
/id=([a-zA-Z0-9-_]+)/, // https://drive.google.com/open?id=FILE_ID
|
||||
/\/d\/([a-zA-Z0-9-_]+)/, // https://drive.google.com/uc?id=FILE_ID&export=download
|
||||
/^([a-zA-Z0-9-_]{25,})$/ // Direct file ID
|
||||
];
|
||||
|
||||
for (const pattern of patterns) {
|
||||
const match = url.match(pattern);
|
||||
if (match) {
|
||||
return match[1];
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check if URL is a Google Drive URL
|
||||
export function isGoogleDriveUrl(url: string): boolean {
|
||||
return url.includes('drive.google.com') || url.includes('googleapis.com');
|
||||
}
|
||||
|
||||
// Download image from Google Drive using the API
|
||||
export async function downloadDriveImage(url: string): Promise<Blob> {
|
||||
const fileId = extractDriveFileId(url);
|
||||
|
||||
if (!fileId) {
|
||||
throw new Error('Could not extract file ID from Google Drive URL');
|
||||
}
|
||||
|
||||
if (!gapi.client.drive) {
|
||||
throw new Error('Google Drive API not loaded');
|
||||
}
|
||||
|
||||
try {
|
||||
// Get file metadata first to check if it exists and is accessible
|
||||
const metadata = await gapi.client.drive.files.get({
|
||||
fileId: fileId,
|
||||
fields: 'id,name,mimeType,size'
|
||||
});
|
||||
|
||||
if (!metadata.result.mimeType?.startsWith('image/')) {
|
||||
throw new Error('File is not an image');
|
||||
}
|
||||
|
||||
// Download the file content
|
||||
const response = await gapi.client.drive.files.get({
|
||||
fileId: fileId,
|
||||
alt: 'media'
|
||||
});
|
||||
|
||||
// The response body is already binary data, convert to blob
|
||||
const binaryString = response.body;
|
||||
const bytes = new Uint8Array(binaryString.length);
|
||||
for (let i = 0; i < binaryString.length; i++) {
|
||||
bytes[i] = binaryString.charCodeAt(i);
|
||||
}
|
||||
|
||||
return new Blob([bytes], { type: metadata.result.mimeType });
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error downloading from Google Drive:', error);
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
||||
throw new Error(`Failed to download image from Google Drive: ${errorMessage}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Create an object URL from image data for display
|
||||
export function createImageObjectUrl(blob: Blob): string {
|
||||
return URL.createObjectURL(blob);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user