Dominant Colors for Lazy-Loading Images

Dominant Colors for Lazy-Loading Images

9b509a6ebaf600e9198dcc3a9a075aa8?s=128

Manuel Wieser

May 19, 2016
Tweet

Transcript

  1. 3.
  2. 4.
  3. 6.
  4. 7.
  5. 8.
  6. 11.
  7. 12.

    const gm = require('gm');
 
 gm('test.jpg') .resize(1, 1) .toBuffer('RGB', (error,

    buffer) => {
 console.log(buffer.slice(0, 3));
 });
  8. 13.
  9. 16.
  10. 17.
  11. 18.
  12. 19.

    let pixels = [];
 let pixel = [];
 
 for

    (let value of buffer.values()) {
 if (pixel.length >= 3) {
 pixels.push(pixel);
 pixel = [];
 }
 pixel.push(value);
 }
 
 km.clusterize(pixels, {k: 1}, (error, result) => {
 result.forEach(cluster => {
 return cluster.centroid.map(val => Math.round(val).toString(16)).join('');
 });
 });
  13. 21.
  14. 22.

    GraphicsMagick
 resize() GraphicsMagick
 colors() k-means Clustering GraphicsMagick
 resize() GraphicsMagick
 colors()

    k-means Clustering GraphicsMagick
 resize() GraphicsMagick
 colors() k-means Clustering
  15. 24.
  16. 28.
  17. 29.
  18. 30.
  19. 31.

    47 49 46 38 39 61 // Header
 01 00

    01 00 80 00 00 // Logical Screen Descriptor
 FF FF FF 00 00 00 // Global Color Table
 21 F9 04 00 00 00 00 00 // Graphics Control Extension
 2C 00 00 00 00 01 00 01 00 00 // Image Descriptor
 02 02 44 01 00 // Image Data
 3B // Trailer 
 data:image/gif;base64,R0lGODlhAQABAIAAAP/// wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==
  20. 32.

    47 49 46 38 39 61 // Header
 01 00

    01 00 80 00 00 // Logical Screen Descriptor
 FF FF FF 00 00 00 // Global Color Table
 2C 00 00 00 00 01 00 01 00 00 // Image Descriptor
 02 02 44 01 00 // Image Data 
 data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACwAAAAAAQABAAACAkQBAA==
  21. 33.

    var header = new Buffer('474946383961', 'hex');
 var logicalScreenDescriptor = new

    Buffer('01000100800100', 'hex');
 var imageDescriptor = new Buffer('2c000000000100010000', 'hex');
 var imageData = new Buffer('0202440100', 'hex');
 
 gm('test.jpg')
 .colors(1)
 .toBuffer('RGB', (error, buffer) => {
 var gif = [
 header,
 logicalScreenDescriptor,
 buffer.slice(0, 3),
 new Buffer([0, 0, 0]),
 imageDescriptor,
 imageData
 ];
 console.log('data:image/gif;base64,' + Buffer.concat(gif).toString('base64'));
 });
  22. 35.

    const gm = require('gm');
 gm('test.jpg')
 .resize(3, 3, '!')
 .toBuffer('GIF', (error,

    buffer) => {
 console.log('data:image/gif;base64,' + 
 buffer.toString('base64'));
 });
  23. 36.
  24. 37.
  25. 39.
  26. 40.
  27. 41.
  28. 42.
  29. 46.

    let svg = `<svg xmlns="http://www.w3.org/2000/svg" 
 viewBox="0 0 ${width} ${height}"></svg>`;

    
 let source = 'data:image/svg+xml;base64,' + new Buffer(svg, 'utf8').toString('base64');