-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathscript.js
More file actions
546 lines (440 loc) · 20.2 KB
/
script.js
File metadata and controls
546 lines (440 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
document.addEventListener('DOMContentLoaded', () => {
// DOM Elements
const uploadArea = document.getElementById('upload-area');
const fileInputLabel = document.querySelector('.file-input-label');
const fileInput = document.getElementById('file-input');
const errorMessage = document.getElementById('error-message');
const dismissError = document.getElementById('dismiss-error');
const previewContainer = document.getElementById('preview-container');
const previewImg = document.getElementById('preview-img');
const originalSizeText = document.getElementById('original-size');
const scaledSizeText = document.getElementById('scaled-size');
const sliceCountText = document.getElementById('slice-count');
const sliceResolutionText = document.getElementById('slice-resolution');
const highResToggle = document.getElementById('high-res-toggle');
const processBtn = document.getElementById('process-btn');
const resetBtn = document.getElementById('reset-btn');
const resultContainer = document.getElementById('result-container');
const slicesPreview = document.getElementById('slices-preview');
const downloadBtn = document.getElementById('download-btn');
const loadingOverlay = document.getElementById('loading-overlay');
const loadingText = document.getElementById('loading-text');
const downloadBtnText = document.querySelector('.btn-text');
const downloadBtnLoader = document.querySelector('.btn-loader');
// Variables to store image data
let originalImage = null;
let slicedImages = [];
let fullViewImage = null;
// Standard Instagram 3:4 aspect ratio
const aspectRatio = 3/4; // width:height ratio
// Standard resolution (for standard mode)
const standardWidth = 1080;
const standardHeight = Math.round(standardWidth / aspectRatio); // Should be 1440
const minSlices = 2;
const halfSliceWidth = standardWidth / 2;
// Show loading overlay with custom message
function showLoading(message) {
loadingText.textContent = message;
loadingOverlay.classList.add('active');
}
// Hide loading overlay
function hideLoading() {
loadingOverlay.classList.remove('active');
}
// Show button loading state
function showButtonLoading(button, textElement, loaderElement) {
button.disabled = true;
textElement.style.opacity = '0.7';
loaderElement.style.display = 'inline-block';
}
// Hide button loading state
function hideButtonLoading(button, textElement, loaderElement) {
button.disabled = false;
textElement.style.opacity = '1';
loaderElement.style.display = 'none';
}
// Event Listeners for drag and drop
uploadArea.addEventListener('dragover', (e) => {
e.preventDefault();
uploadArea.classList.add('drag-over');
});
uploadArea.addEventListener('dragleave', () => {
uploadArea.classList.remove('drag-over');
});
uploadArea.addEventListener('drop', (e) => {
e.preventDefault();
uploadArea.classList.remove('drag-over');
if (e.dataTransfer.files.length) {
handleFile(e.dataTransfer.files[0]);
}
});
// Click on upload area to select file
fileInputLabel.addEventListener('click', (e) => {
e.preventDefault();
fileInput.click();
});
// File input change
fileInput.addEventListener('change', (e) => {
if (e.target.files.length) {
handleFile(e.target.files[0]);
}
});
// Process button
processBtn.addEventListener('click', () => {
showLoading('Generating slices...');
// Use setTimeout to allow the loading overlay to appear before processing
setTimeout(() => {
processImage();
hideLoading();
}, 50);
});
// Reset button
resetBtn.addEventListener('click', () => {
resetApp();
});
// Dismiss error
dismissError.addEventListener('click', () => {
errorMessage.style.display = 'none';
});
// Download button
downloadBtn.addEventListener('click', () => {
showButtonLoading(downloadBtn, downloadBtnText, downloadBtnLoader);
// Use setTimeout to allow the UI to update before processing
setTimeout(() => {
downloadZip().then(() => {
hideButtonLoading(downloadBtn, downloadBtnText, downloadBtnLoader);
}).catch((error) => {
console.error('Error creating zip:', error);
hideButtonLoading(downloadBtn, downloadBtnText, downloadBtnLoader);
showError('There was a problem creating your zip file. Please try again.');
});
}, 50);
});
// High-res toggle change
highResToggle.addEventListener('change', () => {
if (originalImage) {
updateImageDetails();
}
});
// Handle file upload
function handleFile(file) {
// Check if file is image
if (!file.type.match('image.*')) {
showError('Please select an image file');
return;
}
showLoading('Loading your image...');
const reader = new FileReader();
reader.onload = (e) => {
// Create image object to get dimensions
const img = new Image();
img.onload = () => {
hideLoading();
// Check if image has horizontal aspect ratio
if (img.width <= img.height) {
showError('Please upload a panorama image with a horizontal aspect ratio (width > height).');
return;
}
originalImage = {
element: img,
width: img.width,
height: img.height,
src: e.target.result
};
// Update image details
updateImageDetails();
// Show preview
previewImg.src = e.target.result;
// Hide error if shown
errorMessage.style.display = 'none';
// Show preview container
uploadArea.style.display = 'none';
previewContainer.style.display = 'block';
resultContainer.style.display = 'none';
};
img.src = e.target.result;
};
reader.onerror = () => {
hideLoading();
showError('There was an error reading the file. Please try again.');
};
reader.readAsDataURL(file);
}
// Update image details based on selected mode
function updateImageDetails() {
if (!originalImage) return;
const isHighResMode = highResToggle.checked;
const { scaledWidth, scaledHeight, sliceCount, sliceWidth, sliceHeight } = calculateOptimalScaling(
originalImage.width,
originalImage.height,
isHighResMode
);
// Update image details
originalSizeText.textContent = `${originalImage.width}px × ${originalImage.height}px`;
scaledSizeText.textContent = `${scaledWidth}px × ${scaledHeight}px`;
sliceCountText.textContent = sliceCount;
sliceResolutionText.textContent = `${sliceWidth}px × ${sliceHeight}px`;
}
// Calculate optimal scaling to minimize wasted space
function calculateOptimalScaling(originalWidth, originalHeight, highResMode) {
// Default to standard resolution
let sliceWidth = standardWidth;
let sliceHeight = standardHeight;
// For high-res mode: calculate the maximum possible slice size while maintaining aspect ratio
if (highResMode) {
// Calculate maximum height based on original image height
sliceHeight = originalHeight;
// Calculate corresponding width based on 3:4 aspect ratio
sliceWidth = Math.round(sliceHeight * aspectRatio);
}
// Calculate the minimum number of slices needed to contain the image
// while maintaining the original aspect ratio
const originalAspectRatio = originalWidth / originalHeight;
const sliceAspectRatio = sliceWidth / sliceHeight;
// Calculate how many slices we need to maintain the original aspect ratio
let requiredSlices;
if (originalAspectRatio >= sliceAspectRatio) {
// Image is wider than slice ratio - calculate based on width
requiredSlices = Math.ceil(originalAspectRatio / sliceAspectRatio);
} else {
// Image is taller than slice ratio - use minimum slices
requiredSlices = minSlices;
}
// Ensure we have at least the minimum number of slices
const finalSliceCount = Math.max(minSlices, requiredSlices);
// Calculate the total canvas size that maintains the original aspect ratio
// while filling all slices
const totalCanvasWidth = finalSliceCount * sliceWidth;
const totalCanvasHeight = sliceHeight;
// Scale the image to fit this canvas while maintaining aspect ratio
const scaleX = totalCanvasWidth / originalWidth;
const scaleY = totalCanvasHeight / originalHeight;
const scaleFactor = Math.min(scaleX, scaleY);
const scaledImageWidth = Math.round(originalWidth * scaleFactor);
const scaledImageHeight = Math.round(originalHeight * scaleFactor);
return {
scaledWidth: scaledImageWidth,
scaledHeight: scaledImageHeight,
sliceCount: finalSliceCount,
sliceWidth: sliceWidth,
sliceHeight: sliceHeight,
totalCanvasWidth: totalCanvasWidth,
totalCanvasHeight: totalCanvasHeight
};
}
// Show error message
function showError(message) {
const errorText = errorMessage.querySelector('p');
errorText.textContent = message;
errorMessage.style.display = 'block';
// Scroll to error
errorMessage.scrollIntoView({ behavior: 'smooth' });
}
// Process image into slices
function processImage() {
if (!originalImage) return;
const isHighResMode = highResToggle.checked;
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// Calculate optimal scaling and slicing
const { scaledWidth, scaledHeight, sliceCount, sliceWidth, sliceHeight, totalCanvasWidth, totalCanvasHeight } = calculateOptimalScaling(
originalImage.width,
originalImage.height,
isHighResMode
);
// Set canvas dimensions to the total canvas size
canvas.width = totalCanvasWidth;
canvas.height = totalCanvasHeight;
// Fill with white background
ctx.fillStyle = '#FFFFFF';
ctx.fillRect(0, 0, totalCanvasWidth, totalCanvasHeight);
// Scale to FILL the canvas (crop to fill, not fit)
// This ensures no white bars appear in the slices
const scaleX = totalCanvasWidth / originalImage.width;
const scaleY = totalCanvasHeight / originalImage.height;
const scaleFactor = Math.max(scaleX, scaleY); // Use max to fill, not min
const scaledImageWidth = Math.round(originalImage.width * scaleFactor);
const scaledImageHeight = Math.round(originalImage.height * scaleFactor);
// Calculate position to center the scaled image on the total canvas
const offsetX = (totalCanvasWidth - scaledImageWidth) / 2;
const offsetY = (totalCanvasHeight - scaledImageHeight) / 2;
// Draw the image scaled to fill and centered (this will crop if necessary)
ctx.drawImage(
originalImage.element,
0, 0, originalImage.width, originalImage.height,
offsetX, offsetY, scaledImageWidth, scaledImageHeight
);
slicedImages = [];
// Create each slice
for (let i = 0; i < sliceCount; i++) {
const sliceCanvas = document.createElement('canvas');
const sliceCtx = sliceCanvas.getContext('2d');
sliceCanvas.width = sliceWidth;
sliceCanvas.height = sliceHeight;
// Calculate the source area for this slice
const sourceX = i * sliceWidth;
// Draw the slice portion from the main canvas
sliceCtx.drawImage(
canvas,
sourceX, 0, sliceWidth, sliceHeight,
0, 0, sliceWidth, sliceHeight
);
// Convert to data URL
const dataURL = sliceCanvas.toDataURL('image/jpeg', 0.95);
slicedImages.push({
dataURL,
number: i + 1,
width: sliceWidth,
height: sliceHeight
});
}
// Create the full panorama view on white background
createFullViewImage(sliceWidth, sliceHeight);
// Show results
displayResults();
}
// Create a full panorama view on white background with 3:4 aspect ratio
function createFullViewImage(sliceWidth, sliceHeight) {
if (!originalImage) return;
// Create a canvas with the same aspect ratio as the slices
const fullCanvas = document.createElement('canvas');
const fullCtx = fullCanvas.getContext('2d');
// Use the same dimensions as the slices for consistency
fullCanvas.width = sliceWidth;
fullCanvas.height = sliceHeight;
// Fill with white background
fullCtx.fillStyle = '#FFFFFF';
fullCtx.fillRect(0, 0, sliceWidth, sliceHeight);
// Calculate the scale for the panorama to fit within the frame with margins
const margin = Math.round(sliceWidth * 0.08); // 8% margin
const availableWidth = sliceWidth - (margin * 2);
const availableHeight = sliceHeight - (margin * 2);
// Determine which dimension constrains the scaling
const originalAspectRatio = originalImage.width / originalImage.height;
let scaledPanoWidth, scaledPanoHeight;
if (originalAspectRatio > availableWidth / availableHeight) {
// Width is the constraining factor
scaledPanoWidth = availableWidth;
scaledPanoHeight = scaledPanoWidth / originalAspectRatio;
} else {
// Height is the constraining factor
scaledPanoHeight = availableHeight;
scaledPanoWidth = scaledPanoHeight * originalAspectRatio;
}
// Calculate position to center the image
const x = Math.round((sliceWidth - scaledPanoWidth) / 2);
const y = Math.round((sliceHeight - scaledPanoHeight) / 2);
// Draw the scaled panorama centered on the white canvas
fullCtx.drawImage(
originalImage.element,
0, 0, originalImage.width, originalImage.height,
x, y, scaledPanoWidth, scaledPanoHeight
);
// Add a subtle border
fullCtx.strokeStyle = '#EEEEEE';
fullCtx.lineWidth = 1;
fullCtx.strokeRect(x - 1, y - 1, scaledPanoWidth + 2, scaledPanoHeight + 2);
// Convert to data URL
fullViewImage = {
dataURL: fullCanvas.toDataURL('image/jpeg', 0.95),
width: sliceWidth,
height: sliceHeight
};
}
// Display processed slices
function displayResults() {
slicesPreview.innerHTML = '';
// Add the full view as the first item with special styling
if (fullViewImage) {
const fullViewItem = document.createElement('div');
fullViewItem.className = 'slice-item full-view-item';
const img = document.createElement('img');
img.src = fullViewImage.dataURL;
img.alt = 'Full Panorama View';
const label = document.createElement('div');
label.className = 'slice-label';
label.textContent = 'Full View';
const resolution = document.createElement('div');
resolution.className = 'resolution';
resolution.textContent = `${fullViewImage.width}×${fullViewImage.height}`;
fullViewItem.appendChild(img);
fullViewItem.appendChild(label);
fullViewItem.appendChild(resolution);
slicesPreview.appendChild(fullViewItem);
}
// Add all the regular slices
slicedImages.forEach(slice => {
const sliceItem = document.createElement('div');
sliceItem.className = 'slice-item';
const img = document.createElement('img');
img.src = slice.dataURL;
img.alt = `Slice ${slice.number}`;
const number = document.createElement('div');
number.className = 'slice-number';
number.textContent = slice.number;
const resolution = document.createElement('div');
resolution.className = 'resolution';
resolution.textContent = `${slice.width}×${slice.height}`;
sliceItem.appendChild(img);
sliceItem.appendChild(number);
sliceItem.appendChild(resolution);
slicesPreview.appendChild(sliceItem);
});
resultContainer.style.display = 'block';
window.scrollTo({
top: resultContainer.offsetTop - 20,
behavior: 'smooth'
});
}
// Reset app to initial state
function resetApp() {
// Clear file input
fileInput.value = '';
// Hide preview and results
previewContainer.style.display = 'none';
resultContainer.style.display = 'none';
errorMessage.style.display = 'none';
// Show upload area
uploadArea.style.display = 'block';
// Clear image data
originalImage = null;
slicedImages = [];
fullViewImage = null;
// Clear preview
previewImg.src = '';
}
// Download slices as zip file
async function downloadZip() {
if (slicedImages.length === 0) return;
const zip = new JSZip();
const isHighRes = highResToggle.checked;
const folderName = isHighRes ? 'high_res_slices' : 'standard_slices';
// Add the full view as slice_00.jpg if available
if (fullViewImage) {
const imageData = fullViewImage.dataURL.split(',')[1];
zip.file(`${folderName}/slice_00_full_view.jpg`, imageData, { base64: true });
}
// Add each slice to the zip
slicedImages.forEach(slice => {
// Convert data URL to blob
const imageData = slice.dataURL.split(',')[1];
zip.file(`${folderName}/slice_${String(slice.number).padStart(2, '0')}.jpg`, imageData, { base64: true });
});
// Add a readme file explaining the full view
const currentDate = new Date().toISOString().split('T')[0];
const readmeContent =
`Instagram Panorama Slicer - Created by FUTC (@FUTC.Photography on Instagram)
IF YOU LIKE THIS TOOL, PLEASE CONSIDER SUPPORTING ME BY CHECKING OUT MY LIGHTROOM PRESET PACKS (this link includes a heavy discount): https://futc.gumroad.com/l/analogvibes2/panosplitter
This package contains:
- slice_00_full_view.jpg: A complete view of your panorama that fits Instagram's 3:4 aspect ratio
- slice_01.jpg to slice_${String(slicedImages.length).padStart(2, '0')}.jpg: Individual slices of your panorama
For best results on Instagram:
1. Make an instagram carousel post adding slice_01.jpg through slice_${String(slicedImages.length).padStart(2, '0')}.jpg in order
2. Add slice_00_full_view.jpg either as the first or last image in the carousel
`;
zip.file('README.txt', readmeContent);
// Generate zip file
const content = await zip.generateAsync({ type: 'blob' });
saveAs(content, 'instagram_carousel_slices.zip');
}
});