Advertisement
mariodian

Fake image with name initials

Jul 17th, 2015
577
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function generateImage(picture, name){
  2.     if( picture != null )
  3.     {
  4.         return '<img src="' + picture + '" alt="" />';
  5.     }
  6.     else
  7.     {
  8.         // http://jsfiddle.net/tHCsq/2/ - generate colors
  9.         // http://jsfiddle.net/6PfsW/2/ - generate array
  10.         // http://jsfiddle.net/LP8kr/ - shuffling
  11.            
  12.         var colors = ['#007f3f', '#3f7f00', '#b20094', '#b27600', '#997f00', '#990019', '#007f00', '#003bb2', '#7f3f00', '#7700b2', '#990066', '#007f7f', '#00007f', '#1d00b2', '#b21d00', '#7f7f00', '#7f003f', '#00b21d', '#009933', '#993200', '#320099', '#7f007f', '#00b276', '#001999', '#669900', '#3f007f', '#b2003b', '#7f0000', '#7f0099', '#199900', '#94b200', '#0094b2', '#003f7f', '#3bb200', '#006599', '#00997f'];
  13.            
  14.         return '<div class="fake-img"><div class="fake-img-bg" style="background: ' + colors[stringValue(name)] + '">' + nameInitials(name) + '</div></div>';
  15.     }
  16. }
  17.  
  18. function stringValue(string){
  19.     var sum = 0;
  20.    
  21.     for( var i = 0; i < string.length; i++ )
  22.     {
  23.         var code = string.charCodeAt(i);
  24.        
  25.         sum ^= code * (i+1);
  26.     }
  27.    
  28.     return parseInt(Math.round(sum % 36));
  29. }
  30.  
  31. function nameInitials(name){
  32.     var initials = '';
  33.    
  34.     name = '' + removeAccents(name);
  35.    
  36.     var matches = name.match(/\b(\w)/g);
  37.    
  38.     for( var i = 0; i < matches.length; i++ )
  39.     {
  40.         initials += matches[i];
  41.     }
  42.        
  43.     if( initials.length > 2 )
  44.     {
  45.         return initials.substr(0, 2);
  46.     }
  47.    
  48.     if( initials.length < 2 )
  49.     {
  50.         return name.substr(0, 2);
  51.     }
  52.    
  53.     return initials;
  54. }
  55.  
  56. function removeAccents(input){
  57.     var accents     = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇČçčÐĎďÌÍÎÏìíîïĽľÙÚÛÜùúûüÑŇñňŠšŤťŸÿýŽž  ́', // need to hack accent
  58.         accentsOut  = 'AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCCccDDdIIIIiiiiLlUUUUuuuuNNnnSsTtYyyZz ',
  59.         output      = '',
  60.         index       = -1;
  61.    
  62.     for( var i = 0; i < input.length; i++ )
  63.     {
  64.         index = accents.indexOf(input[i]);
  65.        
  66.         if( index != -1 )
  67.         {
  68.             output += typeof accentsOut[index] != 'undefined' ? accentsOut[index] : '';
  69.         }
  70.         else
  71.         {
  72.             output += typeof input[i] != 'undefined' ? input[i] : '';
  73.         }
  74.     }
  75.    
  76.     return output;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement