|
1 | 1 | (function () { |
2 | 2 | window.BlazorInputFile = { |
3 | 3 | init: function init(elem, componentInstance) { |
4 | | - var nextFileId = 0; |
| 4 | + elem._blazorInputFileNextFileId = 0; |
5 | 5 |
|
6 | 6 | elem.addEventListener('change', function handleInputFileChange(event) { |
7 | 7 | // Reduce to purely serializable data, plus build an index by ID |
8 | 8 | elem._blazorFilesById = {}; |
9 | 9 | var fileList = Array.prototype.map.call(elem.files, function (file) { |
10 | 10 | var result = { |
11 | | - id: ++nextFileId, |
| 11 | + id: ++elem._blazorInputFileNextFileId, |
12 | 12 | lastModified: new Date(file.lastModified).toISOString(), |
13 | 13 | name: file.name, |
14 | 14 | size: file.size, |
|
34 | 34 | }); |
35 | 35 | }, |
36 | 36 |
|
| 37 | + toImageFile(elem, fileId, format, maxWidth, maxHeight) { |
| 38 | + var originalFile = getFileById(elem, fileId); |
| 39 | + return createImageBitmap(originalFile.blob) |
| 40 | + .then(function (imageBitmap) { |
| 41 | + return new Promise(function (resolve) { |
| 42 | + var desiredWidthRatio = Math.min(1, maxWidth / imageBitmap.width); |
| 43 | + var desiredHeightRatio = Math.min(1, maxHeight / imageBitmap.height); |
| 44 | + var chosenSizeRatio = Math.min(desiredWidthRatio, desiredHeightRatio); |
| 45 | + |
| 46 | + var canvas = document.createElement('canvas'); |
| 47 | + canvas.width = Math.round(imageBitmap.width * chosenSizeRatio); |
| 48 | + canvas.height = Math.round(imageBitmap.height * chosenSizeRatio); |
| 49 | + canvas.getContext('2d').drawImage(imageBitmap, 0, 0, canvas.width, canvas.height); |
| 50 | + return canvas.toBlob(resolve, format); |
| 51 | + }); |
| 52 | + }) |
| 53 | + .then(function (resizedImageBlob) { |
| 54 | + var result = { |
| 55 | + id: ++elem._blazorInputFileNextFileId, |
| 56 | + lastModified: originalFile.lastModified, |
| 57 | + name: originalFile.name, // Note: we're not changing the file extension |
| 58 | + size: resizedImageBlob.size, |
| 59 | + type: format, |
| 60 | + relativePath: originalFile.relativePath |
| 61 | + }; |
| 62 | + |
| 63 | + elem._blazorFilesById[result.id] = result; |
| 64 | + |
| 65 | + // Attach the blob data itself as a non-enumerable property so it doesn't appear in the JSON |
| 66 | + Object.defineProperty(result, 'blob', { value: resizedImageBlob }); |
| 67 | + |
| 68 | + return result; |
| 69 | + }); |
| 70 | + }, |
| 71 | + |
37 | 72 | readFileData: function readFileData(elem, fileId, startOffset, count) { |
38 | 73 | var readPromise = getArrayBufferFromFileAsync(elem, fileId); |
39 | 74 |
|
|
0 commit comments