forked from mozilla-b2g/gaia
/
ImageEditor.js
1945 lines (1692 loc) · 62.9 KB
/
ImageEditor.js
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file contains Gallery code for editing images
'use strict';
var editedPhotoURL; // The blob URL of the photo we're currently editing
var editSettings; // Settings object to perform edits and initialize the UI
var imageEditor;
var currentEditTool;
var savedEditSettings; // Object to save editSettings before entering edit tool
var editOptionButtons =
Array.slice($('edit-options').querySelectorAll('a.radio.button'), 0);
var editBgImageButtons =
Array.slice($('edit-options').querySelectorAll('a.bgimage.button'), 0);
// Edit mode event handlers
$('edit-exposure-button').onclick = setEditTool.bind(null, 'exposure');
$('edit-crop-button').onclick = setEditTool.bind(null, 'crop');
$('edit-effect-button').onclick = setEditTool.bind(null, 'effect');
$('edit-enhance-button').onclick = setEditTool.bind(null, 'enhance');
$('edit-crop-none').onclick = undoCropHandler;
$('edit-header').addEventListener('action', onCancelButton);
$('edit-tool-apply-button').onclick = applyEditTool;
$('edit-save-button').onclick = saveEditedImage;
editOptionButtons.forEach(function(b) { b.onclick = editOptionsHandler; });
// Ensure there is enough space to store an edited copy of photo n
// and if there is, call editPhoto to do so
function editPhotoIfCardNotFull(n) {
var fileinfo = files[n];
var imagesize = fileinfo.size;
photodb.freeSpace(function(freespace) {
// the edited image might take up more space on the disk, but
// not all that much more
if (freespace > imagesize * 2) {
editPhoto(n);
}
else {
alert(navigator.mozL10n.get('memorycardfull'));
}
});
}
function resizeHandler() {
exposureSlider.resize();
imageEditor.resize();
}
function editPhoto(n) {
editedPhotoIndex = n;
var metadata = files[n].metadata;
editSettings = {
crop: {
x: 0, y: 0, w: metadata.width, h: metadata.height,
cropModeId: 'edit-crop-aspect-free' // selected crop mode element Id
},
exposure: {
sliderThumbPos: 0, // Slider thumb position
gamma: 1
},
effect: {
effectId: 'edit-effect-none', // selected effect mode element id
matrix: ImageProcessor.IDENTITY_MATRIX
},
enhance: {
rgbMinMaxValues: ImageProcessor.default_enhancement
},
isImageEdited: false // flag to store if first edit has occurred
};
// Start looking up the image file
photodb.getFile(files[n].name, gotFile);
function gotFile(file) {
// The image editor does not handle EXIF rotation, so if the image has
// EXIF orientation flags, we alter the image in place before starting
// to edit it. Similarly, if the image is too big for us to decode at
// full size we need to create a downsampled version that is editable.
// For low-memory devices like Tarako, CONFIG_MAX_EDIT_PIXEL_SIZE will
// be set to a non-zero value, and this may cause us to downsample the
// image even further than we would otherwise.
var imagesize = metadata.width * metadata.height;
var maxsize = CONFIG_MAX_EDIT_PIXEL_SIZE || CONFIG_MAX_IMAGE_PIXEL_SIZE;
if (metadata.rotation || metadata.mirrored || imagesize > maxsize) {
showSpinner();
cropResizeRotate(file, null, maxsize || null,
null, metadata,
function(error, rotatedBlob) {
hideSpinner();
if (error) {
console.error('Error while rotating image:', error);
rotatedBlob = file;
}
startEdit(rotatedBlob);
});
}
else {
startEdit(file);
}
}
// This will be called with the file the user is editing or with a rotated
// version of that file
function startEdit(blob) {
// Create the image editor object
// This has to come after setView or the canvas size is wrong.
imageEditor = new ImageEditor(blob,
$('edit-preview-area'),
editSettings);
// Show editor screen and hide edit tool screen
hideEditToolView();
currentEditTool = null;
// Set auto enhance icon to default off state
$('edit-enhance-button').classList.remove('on');
// Set edit screen header title
$('edit-title').setAttribute('data-l10n-id', 'edit');
// Disable save and edit tool apply button until an edit is applied
$('edit-save-button').disabled = true;
$('edit-tool-apply-button').disabled = true;
window.addEventListener('resize', resizeHandler);
// Set the background for all of the image buttons
editedPhotoURL = URL.createObjectURL(blob);
// Use #-moz-samplesize media fragment to downsample images
// so the resulting images are smaller and fits 5 image buttons
// Here we assume image buttons are 50px high
var scale = window.innerWidth / 5 * window.devicePixelRatio *
window.devicePixelRatio * 50 /
(metadata.width * metadata.height);
var sampleSize = Downsample.areaNoMoreThan(scale);
var backgroundImage = 'url(' + editedPhotoURL + sampleSize + ')';
editBgImageButtons.forEach(function(b) {
b.style.backgroundImage = backgroundImage;
});
}
// Display the edit screen
setView(LAYOUT_MODE.edit);
// Set the default option buttons to correspond to those edits
editOptionButtons.forEach(function(b) { b.classList.remove('selected'); });
$('edit-crop-aspect-free').classList.add('selected');
$('edit-effect-none').classList.add('selected');
}
// Crop and Effect buttons call this
function editOptionsHandler() {
// First, unhighlight all buttons in this group and then
// highlight the button that has just been chosen. These
// buttons have radio behavior
var parent = this.parentNode;
var buttons = parent.querySelectorAll('a.radio.button');
Array.forEach(buttons, function(b) { b.classList.remove('selected'); });
this.classList.add('selected');
// Set selected effect or cropMode elementId in editSettings object
// to initialize UI on re-enter of an editMode
if (this.dataset.effect) {
editSettings.effect.effectId =
$('edit-effect-options').getElementsByClassName('selected')[0].id;
} else {
editSettings.crop.cropModeId =
$('edit-crop-options').getElementsByClassName('selected')[0].id;
}
if (this === $('edit-crop-aspect-free'))
imageEditor.setCropAspectRatio();
else if (this === $('edit-crop-aspect-portrait'))
imageEditor.setCropAspectRatio(2, 3);
else if (this === $('edit-crop-aspect-landscape'))
imageEditor.setCropAspectRatio(3, 2);
else if (this === $('edit-crop-aspect-square'))
imageEditor.setCropAspectRatio(1, 1);
else if (this.dataset.effect) {
editSettings.effect.matrix =
ImageProcessor[this.dataset.effect + '_matrix'];
imageEditor.edit();
}
enableSaveAndApplyButtons();
}
/*
* This is the exposure slider component for edit tool. This ought to be
* converted into a reusable slider module, but for now this is a
* custom version that hardcodes things like the -3 to +3 range of values.
*/
var exposureSlider = (function() {
var slider = document.getElementById('exposure-slider');
var bar = document.getElementById('sliderline');
var thumb = document.getElementById('sliderthumb');
var currentExposure = 0;
var dragStart = null;
// prepare gesture detector for slider
var gestureDetector = new GestureDetector(thumb);
gestureDetector.startDetecting();
thumb.addEventListener('pan', function(e) {
var delta = e.detail.absolute.dx;
var exposureDelta = delta / parseInt(bar.clientWidth, 10) * 6;
// For the firt time of pan event triggered
// set start value to current value.
if (!dragStart)
dragStart = currentExposure;
setExposure(dragStart + exposureDelta);
e.preventDefault();
});
thumb.addEventListener('swipe', function(e) {
// when stopping we init the dragStart to be null
// this way we avoid a 'panstart' event
dragStart = null;
e.preventDefault();
});
thumb.addEventListener('touchstart', function(e) {
thumb.classList.add('active');
});
thumb.addEventListener('touchend', function(e) {
thumb.classList.remove('active');
});
function resize() {
forceSetExposure(currentExposure);
}
// Set the thumb position between -3 and +3
function setExposure(exposure) {
// Make sure it is not out of bounds
if (exposure < -3)
exposure = -3;
else if (exposure > 3)
exposure = 3;
// Round to the closest sixteenth
exposure = Math.round(exposure * 16) / 16;
if (exposure === currentExposure)
return;
forceSetExposure(exposure);
}
function forceSetExposure(exposure) {
// Remove left/right 4 pixels of margin
var barWidth = parseInt(bar.clientWidth, 10) - 4 * 2;
var thumbWidth = parseInt(thumb.clientWidth, 10);
var offset = bar.offsetLeft + 4;
// Convert exposure value to a unit coefficient position of thumb center
var unitCoef = (exposure + 3) / 6;
// Convert unitCoef to pixel position of thumb center
var pixel = offset + barWidth * unitCoef;
// Compute pixel position of left edge of thumb
pixel -= thumbWidth / 2;
// Move the thumb to that position
thumb.style.left = pixel + 'px';
// Display exposure value in thumb
thumb.textContent = exposure;
// Don't need to update the currentExposure and dispatch the event if they
// are the same.
if (currentExposure === exposure) {
return;
}
// Remember the new exposure value
currentExposure = exposure;
// Dispatch an event to actually change the image
slider.dispatchEvent(new Event('change', {bubbles: true}));
}
return {
resize: resize,
forceSetExposure: forceSetExposure,
setExposure: setExposure,
getExposure: function() { return currentExposure; }
};
})();
// Handle changes on the slider and turn them into calls to edit the image
(function() {
var requestId = null;
$('exposure-slider').onchange = function() {
if (!imageEditor) // If it has not been created yet
return;
// If there is already a pending request, it will take care of this change
// and we don't have to request a new one.
if (requestId !== null)
return;
requestId = requestAnimationFrame(function() {
requestId = null;
var stops = exposureSlider.getExposure();
// Convert the exposure compensation stops gamma correction value.
var factor = -1; // Adjust this factor to get something reasonable.
var gamma = Math.pow(2, stops * factor);
editSettings.exposure.gamma = gamma;
editSettings.exposure.sliderThumbPos = stops;
enableSaveAndApplyButtons();
imageEditor.edit();
});
};
}());
// Set editTool to respective edit modes on click
// of crop, exposure, effect, enhance.
function setEditTool(editTool) {
// Hide all options
var options = $('edit-options').querySelectorAll('div.edit-options-bar');
Array.forEach(options, function(o) { o.classList.add('hidden'); });
// Hide auto enhance message banner before entering
// an edit tool or cancel of edit screens.
$('edit-enhance-banner').hidden = true;
// Make a copy of editSettings when you enter edit tool
savedEditSettings = clone(editSettings);
// Now select and show the correct UI based on editTool
switch (editTool) {
case 'exposure':
// Show exposure EditTool and hide main edit screen
showEditToolView();
$('exposure-slider').classList.remove('hidden');
$('edit-title').setAttribute('data-l10n-id', 'exposure');
// Set exposure slider thumb position
exposureSlider.forceSetExposure(editSettings.exposure.sliderThumbPos);
break;
case 'crop':
showEditToolView();
$('edit-crop-options').classList.remove('hidden');
$('edit-title').setAttribute('data-l10n-id', 'crop');
// Show crop overlay on entering crop edit tool
imageEditor.edit(function() {
imageEditor.showCropOverlay();
});
break;
case 'effect':
showEditToolView();
$('edit-effect-options').classList.remove('hidden');
$('edit-title').setAttribute('data-l10n-id', 'filters');
break;
case 'enhance':
imageEditor.autoEnhancement(setAutoEnhanceState);
enableSaveAndApplyButtons();
break;
}
// Remember the new edit mode
currentEditTool = editTool;
}
function cancelEditTool() {
// Do any necessary cleanup of the currentEditTool view we're exiting.
switch (currentEditTool) {
case 'exposure':
// On cancel in exposure EditTool restore exposure state
// inside editsettings object.
editSettings.exposure = savedEditSettings.exposure;
break;
case 'crop':
// On cancel in Crop Edit Tool, restore crop state in editSettings object
// and revert selected option node.
$(editSettings.crop.cropModeId).classList.remove('selected');
$(savedEditSettings.crop.cropModeId).classList.add('selected');
editSettings.crop = savedEditSettings.crop;
// In crop edit tool, click of back to original button is different
// from other aspect ratio buttons. Click of back to original -
// (undoCropHandler) set source rectangle crop region to original image
// size and generates new preview. If user cancels after clicking back
// to original, we need to explicitly reset preview and set source
// rectangle crop region to saved values from editSettings.
var isCropped = imageEditor.hasBeenCropped();
if (!isCropped) {
// if crop region is same as original image size,
// cancel out by discarding original preview image.
imageEditor.resetPreview();
// Set source rectangle crop region from editSettings
// to go back to previous cropped size preview.
imageEditor.forceSetCropRegion();
}
break;
case 'effect':
// On cancel in Effect Edit Tool, restore effect state
// in editSettings object and revert selected option node.
$(editSettings.effect.effectId).classList.remove('selected');
$(savedEditSettings.effect.effectId).classList.add('selected');
editSettings.effect = savedEditSettings.effect;
break;
}
// Revert to main edit screen on edit tool cancel
// Update preview image with editSettings object
imageEditor.edit(function() {
imageEditor.hideCropOverlay();
});
$('edit-title').setAttribute('data-l10n-id', 'edit');
// Hide Edit Tool and show main edit screen
hideEditToolView();
currentEditTool = null;
}
// Apply changes made in crop edit tool and go back to edit screen
// Other edit tools - exposure, effects, enhance apply their edits
// as the user interacts with the buttons or slider
function applyEditTool() {
switch (currentEditTool) {
case 'crop':
imageEditor.cropImage(function() {
imageEditor.hideCropOverlay();
});
break;
}
$('edit-title').setAttribute('data-l10n-id', 'edit');
// Hide Edit tool screen
hideEditToolView();
// Reset current edit tool and editSettings saved state to null
currentEditTool = null;
savedEditSettings = null;
}
function onCancelButton() {
// Check for currentEditTool to find if user is cancelling out
// from edit tool screen or main edit screen
if (currentEditTool === null) {
// Exit main edit screen withot saving edited image
exitEdit(false);
} else {
// Cancel edit tool and go back to main edit screen
cancelEditTool();
}
}
function enableSaveAndApplyButtons() {
// Enable Apply and Save buttons if it's first edit and isImageEdited
// is false. For subesquent edits apply and save button stays enabled.
if (!editSettings || editSettings.isImageEdited) {
return;
}
if (imageEditor.hasBeenCropped() ||
editSettings.effect.matrix !==
ImageProcessor.IDENTITY_MATRIX ||
editSettings.enhance.rgbMinMaxValues !==
ImageProcessor.default_enhancement ||
editSettings.exposure.gamma !== 1) {
editSettings.isImageEdited = true;
$('edit-tool-apply-button').disabled = false;
$('edit-save-button').disabled = false;
}
}
// Create deep copy of an object
function clone(obj) {
return JSON.parse(JSON.stringify(obj));
}
// Toggle the auto enhancement on/off.
function setAutoEnhanceState(isEnhanced) {
var statusLabel = $('edit-enhance-status');
var enhanceButton = $('edit-enhance-button');
var banner = $('edit-enhance-banner');
if (isEnhanced) {
showStatus('enhance-on');
enhanceButton.classList.add('on');
} else {
showStatus('enhance-off');
enhanceButton.classList.remove('on');
}
function showStatus(msgId) {
navigator.mozL10n.setAttributes(statusLabel, msgId);
banner.hidden = false;
setTimeout(function() {
banner.hidden = true;
}, 3000);
}
}
// Handle show and hide of edit tool screen
function showEditToolView() {
// Hide Editor toolbar and save button
$('edit-toolbar').classList.add('hidden');
$('edit-save-button').hidden = true;
// Show Edit Tool options and apply button
$('edit-options').classList.remove('hidden');
$('edit-tool-apply-button').hidden = false;
}
function hideEditToolView() {
// Show Editor toolbar and save button
$('edit-toolbar').classList.remove('hidden');
$('edit-save-button').hidden = false;
// Hide Edit Tool options and apply button
$('edit-options').classList.add('hidden');
$('edit-tool-apply-button').hidden = true;
}
function undoCropHandler() {
// Switch to free-form cropping
Array.forEach($('edit-crop-options').querySelectorAll('a.radio.button'),
function(b) { b.classList.remove('selected'); });
$('edit-crop-aspect-free').classList.add('selected');
imageEditor.setCropAspectRatio(); // freeform
// And revert to full-size image
imageEditor.undoCrop();
// Update selected cropModeId to default inside settings object
editSettings.crop.cropModeId = 'edit-crop-aspect-free';
}
function exitEdit(saved) {
// Revoke the blob URL we've been using
URL.revokeObjectURL(editedPhotoURL);
editedPhotoURL = null;
// close the editor object
imageEditor.destroy();
imageEditor = null;
savedEditSettings = null;
editSettings = null;
window.removeEventListener('resize', resizeHandler);
// we want the slider re-zeroed for the next time we come into the editor
exposureSlider.forceSetExposure(0.0);
// We came in to edit mode from fullscreenView. If the user cancels the edit
// go back to fullscreenView. Otherwise, if the user saves the photo, we go
// back to thumbnail list view because that is where the newly saved
// image is going to show up.
// XXX: this isn't really right. Ideally the new photo should show up
// right next to the old one and we should go back to fullscreenView to view
// the edited photo.
if (saved) {
// After we sucessfully save a picture, we need to make sure that the
// current file will point to it. We need a flag for fileCreated(),
// so that the currentFileIndex will stay at 0 which is the newest one.
justSavedEditedImage = true;
// After insert sucessfully, db will call file created and setFile to
// latest file, then we go to fullscreen mode to see the edited picture.
setView(LAYOUT_MODE.fullscreen);
} else {
setView(LAYOUT_MODE.fullscreen);
showFile(currentFileIndex);
}
}
// When the user clicks the save button, we produce a full-size version
// of the edited image, save it into the media database and return to
// photo view mode.
// XXX: figure out what the image number of the edited photo is or will be
// and return to viewing that one. Ideally, edited photos would be grouped
// with the original, rather than by date, but I'm not sure I can
// do that sort order. Ideally, I'd like the mediadb to not generate a
// change event when we manually add something to it or at least have that
// option
function saveEditedImage() {
// Save button disabled to prevent the user triggering multiple
// save operations
$('edit-save-button').disabled = true;
// If we are in crop mode, perform the crop before saving
if ($('edit-crop-button').classList.contains('selected'))
imageEditor.cropImage();
var progressBar = $('save-progress');
// Show progressbar when start to save.
progressBar.classList.remove('hidden');
progressBar.value = 0;
progressBar.max = 110; // Allow an extra 10% time for conversion to blob
imageEditor.getFullSizeBlob('image/jpeg', gotBlob, onProgress);
function onProgress(p, error) {
// If error occurs, reset the save button for user.
if (error) {
$('edit-save-button').disabled = false;
progressBar.value = 0;
return;
}
progressBar.value = Math.floor(p * 100);
}
function gotBlob(blob) {
// Hide progressbar when saved.
progressBar.classList.add('hidden');
var original = files[editedPhotoIndex].name;
var basename, extension, filename;
var version = 1;
var p = original.lastIndexOf('.');
if (p === -1) {
basename = original;
extension = '';
}
else {
basename = original.substring(0, p);
extension = original.substring(p);
}
// Create a filename for the edited image. Loop if necessary and
// increment the version number until we find a version a name that
// is not in use.
// XXX: this loop is O(n^2) and slow if the user saves many edits
// of the same image.
filename = basename + '.edit' + version + extension;
while (files.some(function(i) { return i.name === filename; })) {
version++;
filename = basename + '.edit' + version + extension;
}
// Now that we have a filename, save the file This will send a
// change event, which will cause us to rebuild our thumbnails.
// For now, the edited image will become the first thumbnail since
// it si the most recent one. Ideally, I'd like a more
// sophisticated sort order that put edited sets of photos next to
// each other.
photodb.addFile(filename, blob);
// We're done.
exitEdit(true);
progressBar.value = 0;
}
}
/*
* ImageEditor.js: simple image editing and previews in a <canvas> element.
*
* Display an edited version of the specified image in a <canvas> element
* inside the specified container element. The image (or cropped region of
* the image) will be displayed as large as possible within the container's
* area. Edits is an object that specifies the edits to apply to the image.
* The edits object may include these properties:
*
* gamma: a float specifying gamma correction
* matrix: a 4x4 matrix that represents a transformation of each rgba pixel.
* this can be used to convert to bw or sepia, for example.
*
* In addition to previewing the image, this class also defines a
* getFullSizeBlob() function that creates a full-size version of the
* edited image.
*
* This class also handles cropping. See:
*
* showCropOverlay()
* hideCropOverlay()
* cropImage()
* undoCrop()
*
* This code expects WebGL GLSL shader programs in scripts with ids
* edit-vertex-shader and edit-fragment-shader. It dynamically creates
* canvas elements with ids edit-preview-canvas and edit-crop-canvas.
* The stylesheet includes static styles to position those dyanamic elements.
*/
function ImageEditor(imageBlob, container, edits, ready, croponly) {
this.imageBlob = imageBlob;
this.imageURL = URL.createObjectURL(imageBlob);
this.container = container;
this.edits = edits || {};
this.croponly = !!croponly;
this.source = {}; // The source rectangle (crop region) of the image
this.dest = {}; // The destination (preview) rectangle of canvas
this.cropRegion = {}; // Region displayed in crop overlay during drags
// The canvas that displays the preview
this.previewCanvas = document.createElement('canvas');
this.previewCanvas.id = 'edit-preview-canvas'; // for stylesheet
this.container.appendChild(this.previewCanvas);
this.previewCanvas.width = this.previewCanvas.clientWidth;
this.previewCanvas.height = this.previewCanvas.clientHeight;
// prepare gesture detector for ImageEditor
this.gestureDetector = new GestureDetector(container, { panThreshold: 3 });
this.gestureDetector.startDetecting();
// preset the scale to something useful in case resize() gets called
// before generateNewPreview()
this.scale = 1.0;
// Once a preview image is created, we have to "upload" it to WebGL.
// But we only want to do this once. This flag is true if the preview
// has not been uploaded. We set it each time we create a new preview image.
// And clear it each time we call the ImageProcessor's draw() method.
// We pass the flag to draw() to tell it whether it needs to upload
// before drawing. See bug 934787.
this.needsUpload = true;
var self = this;
if (this.croponly) {
this.original = null;
this.preview = new Image();
this.preview.src = this.imageURL;
this.preview.onload = function() {
self.displayCropOnlyPreview();
if (ready)
ready();
};
}
else {
// Start loading the image into a full-size offscreen image
this.original = new Image();
this.original.src = this.imageURL;
this.preview = new Image();
this.preview.src = null;
var contextRestoreCallback = function() {
self.needsUpload = true;
self.edit();
};
this.processor = new ImageProcessor(this.previewCanvas, null,
contextRestoreCallback);
// When the image loads display it
this.original.onload = function() {
// Initialize the crop region to the full size of the original image
self.resetCropRegion();
self.resetPreview();
// Display an edited preview of it
self.edit(function() {
// If the constructor had a ready callback argument, call it now
if (ready)
ready();
});
};
}
}
ImageEditor.prototype.displayCropOnlyPreview = function() {
var previewContext = this.previewCanvas.getContext('2d');
var scalex = this.previewCanvas.width / this.preview.width;
var scaley = this.previewCanvas.height / this.preview.height;
var scale = Math.min(Math.min(scalex, scaley), 1);
var previewWidth = Math.floor(this.preview.width * scale);
var previewHeight = Math.floor(this.preview.height * scale);
var previewX = Math.floor((this.previewCanvas.width - previewWidth) / 2);
var previewY =
Math.floor((this.previewCanvas.height - previewHeight) / 2);
previewContext.drawImage(this.preview,
previewX, previewY,
previewWidth, previewHeight);
this.scale = scale;
this.dest.x = previewX;
this.dest.y = previewY;
this.dest.width = previewWidth;
this.dest.height = previewHeight;
};
ImageEditor.prototype.generateNewPreview = function(callback) {
var self = this;
// infer the previewHeight such that the aspect ratio stays the same
var scalex = this.previewCanvas.width / this.source.width;
var scaley = this.previewCanvas.height / this.source.height;
this.scale = Math.min(Math.min(scalex, scaley), 1);
var previewWidth = Math.floor(this.source.width * this.scale);
var previewHeight = Math.floor(this.source.height * this.scale);
// Update edits with new dimensions
this.edits.crop.x = this.source.x;
this.edits.crop.y = this.source.y;
this.edits.crop.w = this.source.width;
this.edits.crop.h = this.source.height;
// Create a preview image
var canvas = document.createElement('canvas');
canvas.width = previewWidth;
canvas.height = previewHeight;
// In this case, we only need graphic 2d to do the scaling. The
// willReadFrequently option makes canvas use software graphic 2d. This can
// skip a bug of GPU version, bug 960276.
var context = canvas.getContext('2d', { willReadFrequently: true });
// Draw that region of the image into the canvas, scaling it down
context.drawImage(this.original, this.source.x, this.source.y,
this.source.width, this.source.height,
0, 0, previewWidth, previewHeight);
// Feed the thumbnail's pixel data as input to the image enhancement worker.
if (imageEditor) {
var imageData = context.getImageData(0, 0, previewWidth, previewHeight);
imageEditor.prepareAutoEnhancement(imageData.data);
}
canvas.toBlob(thumbnailReady, 'image/jpeg');
function thumbnailReady(thumbnail) {
self.preview.src = URL.createObjectURL(thumbnail);
self.preview.onload = function() {
// Set a flag to tell the ImageProcessor to upload the image again
self.needsUpload = true;
callback();
};
};
};
ImageEditor.prototype.resetPreview = function() {
if (this.preview.src) {
URL.revokeObjectURL(this.preview.src);
this.preview.removeAttribute('src');
$('edit-enhance-button').classList.add('disabled');
}
};
ImageEditor.prototype.resize = function() {
var self = this;
var canvas = this.previewCanvas;
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
// Save the crop region (scaled up to full image dimensions)
var savedCropRegion = {};
var hadCropOverlay = this.isCropOverlayShown();
if (hadCropOverlay) {
savedCropRegion.left = this.cropRegion.left / this.scale;
savedCropRegion.top = this.cropRegion.top / this.scale;
savedCropRegion.right = this.cropRegion.right / this.scale;
savedCropRegion.bottom = this.cropRegion.bottom / this.scale;
this.hideCropOverlay();
}
// Now update the preview image. This is done differently in the
// croponly case and in the regular image editing case
if (this.croponly) {
this.displayCropOnlyPreview();
restoreCropRegion();
}
else {
this.resetPreview();
this.edit(restoreCropRegion);
}
// Restore the crop region to what it was before the resize
function restoreCropRegion() {
if (hadCropOverlay) {
// showCropOverlay normally resets cropRegion to the full extent,
// so we need to pass in a new crop region to use
var newRegion = {};
newRegion.left = Math.floor(savedCropRegion.left * self.scale);
newRegion.top = Math.floor(savedCropRegion.top * self.scale);
newRegion.right = Math.floor(savedCropRegion.right * self.scale);
newRegion.bottom = Math.floor(savedCropRegion.bottom * self.scale);
self.showCropOverlay(newRegion);
}
}
};
ImageEditor.prototype.destroy = function() {
if (this.processor) {
this.processor.destroy();
this.processor = null;
}
if (this.original) {
this.original.src = '';
this.original = null;
}
if (this.preview) {
if (this.preview.src !== this.imageURL) {
URL.revokeObjectURL(this.preview.src);
}
this.preview.src = '';
this.preview = null;
}
URL.revokeObjectURL(this.imageURL);
if (this.previewCanvas) {
this.container.removeChild(this.previewCanvas);
// Setting the canvas size to 0 causes a WebGL error so we don't do it
// this.previewCanvas.width = 0;
this.previewCanvas = null;
}
this.hideCropOverlay();
this.gestureDetector.stopDetecting();
this.gestureDetector = null;
};
// Preview the image with the specified edits applied. If edit is omitted,
// displays the original image. Clients should call this function when the
// desired edits change or when the size of the container changes (on
// orientation change events, for example)
ImageEditor.prototype.edit = function(callback) {
if (!this.preview.src) {
var self = this;
this.generateNewPreview(function() {
self.finishEdit(callback);
});
} else {
this.finishEdit(callback);
}
};
ImageEditor.prototype.finishEdit = function(callback) {
var canvas = this.previewCanvas;
var xOffset = Math.floor((canvas.width - this.preview.width) / 2);
var yOffset = Math.floor((canvas.height - this.preview.height) / 2);
this.dest.x = xOffset;
this.dest.y = yOffset;
this.dest.width = this.preview.width;
this.dest.height = this.preview.height;
this.processor.draw(this.preview, this.needsUpload,
0, 0, this.preview.width, this.preview.height,
this.dest.x, this.dest.y, this.dest.width,
this.dest.height, this.edits);
this.needsUpload = false;
if (callback) {
callback();
}
};
// Apply the edits offscreen and pass the full-size edited image as a blob
// to the specified callback function. The code here is much like the
// code above in edit().
//
// This function releases the this.original image so you should only call
// it to get the edited image when you are done with the ImageEditor.
//
ImageEditor.prototype.getFullSizeBlob = function(type, done, progress) {
const TILE_SIZE = 512;
var self = this;
// Create an offscreen canvas and copy the image into it
var canvas = document.createElement('canvas');
canvas.width = this.source.width; // "full size" is cropped image size
canvas.height = this.source.height;
var context = canvas.getContext('2d', { willReadFrequently: true });
context.drawImage(this.original,
this.source.x, this.source.y,
this.source.width, this.source.height,
0, 0, this.source.width, this.source.height);
// As soon as we've copied the original image into the canvas we are
// done with the original and should release it to reduce memory usage.
this.original.src = '';
// How many pixels do we have to process? How many have we processed so far?
var total_pixels = canvas.width * canvas.height;
var processed_pixels = 0;
function makeTileList(imageWidth, imageHeight, tileWidth, tileHeight) {
var tiles = [];
var x = 0, y = 0;
while (y < imageHeight) {
x = 0;
while (x < imageWidth) {
var tile = {x: x, y: y, w: tileWidth, h: tileHeight};
if (x + tileWidth > imageWidth)
tile.w = imageWidth - x;
if (y + tileHeight > imageHeight)
tile.h = imageHeight - y;
tiles.push(tile);
x += tileWidth;
}
y += tileHeight;
}
return tiles;
}
// Create a smaller tile canvas.
var tile = document.createElement('canvas');
tile.width = tile.height = TILE_SIZE;
// Create an ImageProcessor object that renders into the tile.
var processor = new ImageProcessor(tile);
// Divide the image into a set of tiled rectangles
var rectangles = makeTileList(this.source.width, this.source.height,
tile.width, tile.height);
processNextTile();
// Process one tile of the original image, copy the processed tile
// to the full-size canvas, and then return to the event queue.
function processNextTile() {