Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <section>
  <div>
    <h3>Alpha rgb blacken & trim threshold:</h3>    
    <div class="slider athreshold"></div><span class="number">0</span>
  </div>
  <div>
    <h3>How to handle color of fully transparent pixels:</h3>
    <label><input type="radio" name="tpixels" value="avg" checked /> Use average color</label><br/>
    <label><input type="radio" name="tpixels" value="exp"/> Expand color</label>
    <label><input type="radio" name="tpixels" value="expblur"/> Expand color with blur</label>
  </div>
  <div>
    <h3>Upload transparent PNG File:</h3>
    <input type="file" id="files" name="files[]"/><br/>
    <label><input type="checkbox" name="trim"/> Trim Transparent areas</label>
  </div>
</section>

<section>
  <div>
    <h3>Compression RGB:</h3>
    <div class="slider comp rgb"></div><span class="number">65%</span>
    <br/>    
    <label>JPG <input type="radio" name="rgbmode" value="jpg" CHECKED/></label>
    <label>PNG <input type="radio" name="rgbmode" value="png"/></label>
  </div>
  <div>
    <h3>Compression Alpha:</h3>
    <div class="slider comp alpha"></div><span class="number">65%</span>
    <br/>    
    <label>JPG <input type="radio" name="alphamode" value="jpg" CHECKED/></label>
    <label>PNG <input type="radio" name="alphamode" value="png"/></label>
  </div>  
</section>

<section>
  <div>
    <h3>Result:</h3>
    <output id="list"></output>
  </div>
  <div>
    <h3>Code SVG with embedded JPG source, this can be put inline in HTML code.</h3>
    <span class="svgsize"></span>
    <textarea id="codeembedded" class="code"></textarea>
  </div>
  <div>
    <h3>Now it gets deep: complete SVG with embedded image as "optimized encoded" data URL!</h3>
    <span class="svgsizeurl"></span>
    <textarea id="codesvg64" class="code"></textarea>
  </div>
</section>
              
            
!

CSS

              
                body {
  background:#000;
  color:#ffffff;
  padding:15px;
}
* {
  box-sizing:border-box;
}
h1,h2,h3 {
  margin:10px 0;
  //background:linear-gradient(to right,rgba(51,51,51,0),#333 50%), linear-gradient(to bottom, #000,rgba(0,0,0,0));
  background:linear-gradient(#777,rgba(255,255,255,0));
  // border:1px dotted #ccc;
  text-shadow:1px 1px 2px rgba(0,0,0,0.75);
  box-shadow:0px -2px 2px rgba(0,0,0,0.5);
  //border-bottom:none;
  border-radius:10px 10px 0 0;
  padding:4px 10px;
}
.slider {
  width:300px;
  display:inline-block;
}
.container > * {
  max-width:50%;
}
.container:hover > svg {
  max-width:none;
}
a {
  color:#eeeeee;
}
.code {
  width:95%;
  height:20vh;
  margin:20px;
}
section {  
  border:#000 2px solid;
  padding:20px;
  background:radial-gradient(#999,#333),linear-gradient(#666 0px,rgba(0,0,0,0) 15px),linear-gradient(to top,#666 0px,rgba(0,0,0,0) 15px),linear-gradient(to right, #666 0px, rgba(0,0,0,0) 20px),linear-gradient(to left, #666 0px, rgba(0,0,0,0) 20px);
  column-width: 400px;
  &:not(:last-of-type) {
     border-bottom:none; 
  }  
  &:first-of-type {
    border-radius:20px 20px 0 0;

  }
  &:last-of-type {
    border-radius:0 0 20px 20px;
  }
  > div:not(.slider) {
    break-inside:avoid;
    padding:5px 10px 15px 10px;  
  }
  .number, a[download], .container span {
    font-size:20px;
    margin:5px;
    padding:10px;
    background:#333;
    border-radius:10px;
  }
  .container {
    a, span {
      display:block;
      text-align:center;
    }
  }
  input {
    margin-top:10px;
  }
}
              
            
!

JS

              
                  var imageCVs = [],
      $output = $('#list'),
      mskID = 0,
      cvRGB,
      cvAlpha;

  function trimImageData(imgData) {
    var top = null,
      bottom = null,
      left = null,
      right = null,
      dir = 1,
      iw4 = imgData.width * 4,
      thresh = $('.slider.athreshold').slider("values", 0);
    outer:
      for (var yc = 0; yc < imgData.height; yc += dir) {
        var aa = false,
          pos = yc * iw4 + 3;
        for (var xc = 0; xc < imgData.width; xc++, pos += 4) {
          if (imgData.data[pos] > thresh) {
            aa = true;
            break;
          }
        }
        if (aa && dir > 0 && top === null) {
          top = yc;
          dir = -1;
          yc = imgData.height;
        } else if (aa && dir < 0 && bottom === null) {
          bottom = yc + 1;
          break outer;
        }
      }
    console.log("Bottom:" + bottom + " (" + imgData.height + ")");
    if (top === null) top = 0;
    if (bottom === null) bottom = imgData.height;
    dir = 1;
    var topOff = top * iw4;
    outer2:
      for (var xc = 0; xc < imgData.width; xc += dir) {
        var pos = topOff + (xc * 4) + 3,
          aa = false;
        for (var yc = top; yc < bottom; yc++, pos += iw4) {
          if (imgData.data[pos] > thresh) {
            aa = true;
            break;
          }
        }
        if (aa && dir > 0 && left === null) {
          left = xc;
          dir = -1;
          xc = imgData.width;
        } else if (aa && dir < 0 && right === null) {
          right = xc + 1;
          break outer2;
        }
      }
    console.log("left:" + left + " right:" + right + "(" + imgData.width + ")");
    if (left === null) left = 0;
    if (right === null) right = imgData.width;
    if (left == 0 && top == 0 && bottom == imgData.height && right == imgData.width) return imgData;
    var cv = $('<canvas/>')[0],
      ctx = cv.getContext('2d');
    cv.width = right - left;
    cv.height = bottom - top;
    ctx.putImageData(imgData, -left, -top);
    imgData = ctx.getImageData(0, 0, cv.width, cv.height);
    return imgData;
  }

  var img;

  function reMask() {
    if (img) {
      $(img).trigger('load');
    } 
  }

  function handleFileSelect(evt) {
    var files = evt.target.files;    
    for (var i = 0, f; f = files[i]; i++) {      
      if (!f.type.match('image.*')) {
        continue;
      }
      var reader = new FileReader();
      
      reader.onload = (function(theFile) {
        return function(e) {

          var $cv = $('<canvas/>'),
            cv = $cv[0],
            ctx = cv.getContext('2d'),
            imgData,
            imgDataAlpha,            
            $span = $('<span/>'),
            $jpg = $('<img/>'),
            paintBack = false;
          
          img = new Image();
          img.onload = function() {
            var w = img.width,
                h = img.height;
            cv.width = w;
            cv.height = h * 2;
            ctx.drawImage(img, 0, 0);
            imgData = ctx.getImageData(0, 0, w, h);
            if ($('#trim').prop('checked')) {
              imgData = trimImageData(imgData);
              w = imgData.width;
              h = imgData.height;
              cv.width = w;
              cv.height = h * 2;
            }            
            imgDataAlpha = ctx.createImageData(w, h);
            
            var fillMode = $('input[name=tpixels]:checked').val(),
                pos = 0,
                imgDataCopy = new Uint8ClampedArray(imgData.data),
                thresh = $('.slider.athreshold').slider("values", 0);                
            
            if (thresh < 1) thresh = 1;            
            if (fillMode == 'avg') {
              var allR, allG, allB, ca = 0;
              allR = 0;
              allG = 0;
              allB = 0;
              for (var yc = 0; yc < h; yc++) {
                var rowR = 0,
                    rowG = 0,
                    rowB = 0,
                    cRow = 0;
                for (var xc = 0; xc < w; xc++, pos += 4) {
                  var a = imgData.data[pos + 3];
                  imgData.data[pos + 3] = 0xff;
                  if (a < thresh) {
                    a = 0;
                  } else {
                    rowR += imgData.data[pos];
                    rowG += imgData.data[pos + 1];
                    rowB += imgData.data[pos + 2];
                    cRow++;
                  }
                  imgDataAlpha.data[pos] = a;
                  imgDataAlpha.data[pos + 1] = a;
                  imgDataAlpha.data[pos + 2] = a;
                  imgDataAlpha.data[pos + 3] = 0xff;
                }
                if (cRow) {
                  rowR /= cRow;
                  rowG /= cRow;
                  rowB /= cRow;
                  allR += rowR;
                  allG += rowG;
                  allB += rowB;
                  ca++;
                }
              }
              if (ca) {
                allR /= ca;
                allG /= ca;
                allB /= ca;
              }
              for (pos = 0, yc = 0; yc < h; yc++) {
                for (xc = 0; xc < w; xc++, pos += 4) {
                  var a = imgDataCopy[pos + 3];
                  if (a < thresh) {
                    imgData.data[pos] = allR;
                    imgData.data[pos + 1] = allG;
                    imgData.data[pos + 2] = allB;
                  }
                }
              }
            } else {              
              var lastPos = false;
              var spans = [];
              pos = w*h*4;
              while (pos-=4) {
                var a = imgDataCopy[pos+3];
                if (a < thresh) {
                  a=0;
                  if (lastPos===false) lastPos = pos;
                } else {
                  if (lastPos!==false) {
                    spans.push({
                      r:imgData.data[pos],
                      g:imgData.data[pos+1],
                      b:imgData.data[pos+2],
                      from:pos+4,
                      to:lastPos
                    });
                    lastPos = false;
                  }
                }
                imgDataAlpha.data[pos] = a;
                imgDataAlpha.data[pos + 1] = a;
                imgDataAlpha.data[pos + 2] = a;
                imgDataAlpha.data[pos + 3] = 0xff;
                imgData.data[pos+3] = 255;
              }
              if (lastPos!==false && spans.length) {
                var lastSpan = spans[spans.length-1];
                spans.push({
                  r:lastSpan.r,
                  g:lastSpan.g,
                  b:lastSpan.b,
                  from:0,
                  to:lastPos
                });
              }
              var i = spans.length;
              while (i--) {
                var span = spans[i];
                for (pos = span.from; pos <= span.to; pos+=4) {                               imgData.data[pos] = span.r;
                  imgData.data[pos+1] = span.g;
                  imgData.data[pos+2] = span.b;
                  
                }
              }
              
              if (fillMode=="expblur") {
                for (var i=0;i<8;i++) {
                 for (xc=0;xc<w;xc++) {
                   pos = xc*4;
                   var lastColorR = -1;
                   var lastColorB = -1;
                   var lastColorG = -1;
                   for (yc=0;yc<h;yc++,pos+=w*4) {
                     var a = imgDataCopy[pos+3];
                     if (a<thresh) {
                       if (lastColorR>=0) {
                         var r = imgData.data[pos],
                             g = imgData.data[pos+1],
                             b = imgData.data[pos+2];
                         imgData.data[pos] = lastColorR;
                         imgData.data[pos+1] = lastColorG;
                         imgData.data[pos+2] = lastColorB;
                         lastColorR += r;
                         lastColorG += g;
                         lastColorB += b;
                         lastColorR *=0.5;
                         lastColorG *=0.5;
                         lastColorB *=0.5;
                       } else {
                         lastColorR = imgData.data[pos];
                         lastColorG = imgData.data[pos+1];
                         lastColorB = imgData.data[pos+2];
                       }
                     }
                   }
                 }
               }
              }
            }

            //ctx.clearRect(0, 0, cv.width, cv.height);
            //ctx.putImageData(imgData, 0, 0);
            //ctx.putImageData(imgDataAlpha, 0, h);
            //imageCVs.push(cv);
            //insertCVasJPG(cv);
            cvRGB = imgData2Canvas(imgData);
            cvAlpha = imgData2Canvas(imgDataAlpha);
            insertImageData(cvRGB,cvAlpha);
            
          }
          img.src = e.target.result;
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

  function imgData2Canvas(imgData) {
    var cv = $('<canvas/>')[0],
        ctx = cv.getContext('2d')
    cv.width = imgData.width;
    cv.height = imgData.height;
    ctx.putImageData(imgData,0,0);
    return cv;
  }

  function alphaSVG(imgRGB,imgAlpha,w,h) {    
    var svg =
        '<svg width="'+w+'" height="'+h+'" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 '+w+' '+h+'">'+
        '<defs><mask id="msk">'+
          '<image xlink:href="' + imgAlpha + '" width="' + w + '" height="' + h + '"/>'+
        '</mask></defs>' +
      '<image xlink:href="' + imgRGB + '" width="' + w + '" height="' + h + '" mask="url(#msk)"/>'+
        '</svg>';
    return svg;
  }

  function urlEncodeSVG(svg) {
    svg = svg.replace(/"/g,"'").replace(/[\t\n\r]/g,'').replace(/[%&#<>{}]/g,function(ch) {return '%'+ch.charCodeAt(0).toString(16);});
    return 'data:image/svg+xml,'+svg;
  } 

  function insertImageData(cvRGB,cvAlpha) {
    var imgData = {};
    $.each(['rgb','alpha'],function(idx) {
      var sliderValue = $('.slider.comp.'+this).slider("values",0)*0.01,
          cv = idx==0 ? cvRGB: cvAlpha,
          isJPG = $('input[name='+this+'mode]:checked').val()=='jpg',
          b64 = cv.toDataURL(isJPG ? 'image/jpeg' : 'image/png', sliderValue)
      
      imgData[this] = b64;
    });
    var svg = alphaSVG(imgData.rgb,imgData.alpha,cvRGB.width,cvRGB.height),
        svgURL = urlEncodeSVG(svg)
    $('#codeembedded').text(svg);
    $('#codesvg64').text(svgURL);
    writeSize($('.svgsize'),svg);
    writeSize($('.svgsizeurl'),svgURL);
    $('#list').html(svg);
  }

function rePack() {
  console.log("rePack");
  insertImageData(cvRGB,cvAlpha);
}

  function writeSize($elm,data) {
    $elm.text(Math.round(data.length*6/8));
  }

  $('#files').on('change', handleFileSelect);
  $('input[name=tpixels], input[name=trim]').on('change', reMask);
  $('.slider.comp').slider({
    value: 65,
    orientation: "horizontal",
    min: 0,
    max: 100,
    change: function() {
      var $s = $(this);
      var v = $s.slider("values", 0);
      $s.next().text(v+"%");
      rePack();
    }
  });
  $('input[type="radio"]').on('change',function() {
    rePack();
  });
  $('.slider.athreshold').slider({
    value: 0,
    orientation: "horizontal",
    min: 0,
    max: 255,
    change: function() {
      var $s = $('.slider.athreshold');
      var v = $s.slider("values", 0);
      $s.next().text(v);
      reMask();
    }
  });
              
            
!
999px

Console