-
Notifications
You must be signed in to change notification settings - Fork 4k
/
image-corrector.js
56 lines (44 loc) · 1.11 KB
/
image-corrector.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
/**
* WordPress dependencies
*/
import { createBlobURL } from '@wordpress/blob';
/**
* Browser dependencies
*/
const { atob, File } = window;
export default function( node ) {
if ( node.nodeName !== 'IMG' ) {
return;
}
if ( node.src.indexOf( 'file:' ) === 0 ) {
node.src = '';
}
// This piece cannot be tested outside a browser env.
if ( node.src.indexOf( 'data:' ) === 0 ) {
const [ properties, data ] = node.src.split( ',' );
const [ type ] = properties.slice( 5 ).split( ';' );
if ( ! data || ! type ) {
node.src = '';
return;
}
let decoded;
// Can throw DOMException!
try {
decoded = atob( data );
} catch ( e ) {
node.src = '';
return;
}
const uint8Array = new Uint8Array( decoded.length );
for ( let i = 0; i < uint8Array.length; i++ ) {
uint8Array[ i ] = decoded.charCodeAt( i );
}
const name = type.replace( '/', '.' );
const file = new File( [ uint8Array ], name, { type } );
node.src = createBlobURL( file );
}
// Remove trackers and hardly visible images.
if ( node.height === 1 || node.width === 1 ) {
node.parentNode.removeChild( node );
}
}