Call URL.revokeObjectURL for created URLs (#1858)

* Call URL.revokeObjectURL for created URLs

* Refactor image usage
This commit is contained in:
toasted-nutbread 2021-07-29 21:16:55 -04:00 committed by GitHub
parent a0fa67d57c
commit b99850ed54
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -424,9 +424,10 @@ class DictionaryImporter {
} }
// Load image data // Load image data
let image; let width;
let height;
try { try {
image = await this._loadImageBase64(mediaType, content); ({width, height} = await this._getImageResolution(mediaType, content));
} catch (e) { } catch (e) {
throw createError('Could not load image'); throw createError('Could not load image');
} }
@ -436,8 +437,8 @@ class DictionaryImporter {
dictionary, dictionary,
path, path,
mediaType, mediaType,
width: image.naturalWidth, width,
height: image.naturalHeight, height,
content content
}; };
media.set(path, mediaData); media.set(path, mediaData);
@ -461,22 +462,29 @@ class DictionaryImporter {
} }
/** /**
* Attempts to load an image using a base64 encoded content and a media type. * Attempts to load an image using a base64 encoded content and a media type
* and returns its resolution.
* @param mediaType The media type for the image content. * @param mediaType The media type for the image content.
* @param content The binary content for the image, encoded in base64. * @param content The binary content for the image, encoded in base64.
* @returns A Promise which resolves with an HTMLImageElement instance on * @returns A Promise which resolves with {width, height} on success,
* successful load, otherwise an error is thrown. * otherwise an error is thrown.
*/ */
_loadImageBase64(mediaType, content) { _getImageResolution(mediaType, content) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const image = new Image(); const image = new Image();
const eventListeners = new EventListenerCollection(); const eventListeners = new EventListenerCollection();
eventListeners.addEventListener(image, 'load', () => { const cleanup = () => {
image.removeAttribute('src');
URL.revokeObjectURL(url);
eventListeners.removeAllEventListeners(); eventListeners.removeAllEventListeners();
resolve(image); };
eventListeners.addEventListener(image, 'load', () => {
const {naturalWidth: width, naturalHeight: height} = image;
cleanup();
resolve({width, height});
}, false); }, false);
eventListeners.addEventListener(image, 'error', () => { eventListeners.addEventListener(image, 'error', () => {
eventListeners.removeAllEventListeners(); cleanup();
reject(new Error('Image failed to load')); reject(new Error('Image failed to load'));
}, false); }, false);
const blob = MediaUtil.createBlobFromBase64Content(content, mediaType); const blob = MediaUtil.createBlobFromBase64Content(content, mediaType);