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 is required to process package imports. If you need a different preprocessor remove all packages first.

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

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

              
                <div class="image-container">
  <div class="upload-container">
    <input id="file" type="file"/>
  </div>
  <div class="image-preview-container">
    <image class="preview origin"/>
  </div>
  <div class="image-preview-container">
    <image class="preview compress"/>
  </div>
  <div class="massage"></div>
</div>
              
            
!

CSS

              
                body,html,.image-container {
  width: 100%;
  height: 100%;
  background-color: rgba(51, 204, 237, 0.8);
  color: #fff;
  margin: 0;
  padding: 0;
}

.image-preview-container {
  width: 150px;
  
  .preview {
      width: 150px;
  }
}
              
            
!

JS

              
                handleChange = async (e, compressRatio = 0.9) => {
  const file = e.target.files[0];
  const { base64file, paddingTop } = await handleFile(file);
  const { compressedBase64File } = await handleCompressFile(
    file,
    compressRatio
  );
  const origin = base64toBlob(base64file);
  const compress = base64toBlob(compressedBase64File);
  const originSize = (origin.size / 1000).toFixed(2);
  const compressSize = (compress.size / 1000).toFixed(2);
  const compressRate = `${(
    (originSize - compressSize) /
    originSize *
    100
  ).toFixed(2)}%`;
  return {
    originStyle: {
      backgroundImage: `url(${base64file})`,
      paddingTop
    },
    compressStyle: {
      backgroundImage: `url(${compressedBase64File})`,
      paddingTop
    },
    originSize,
    compressSize,
    compressRate,
    base64file,
    compressedBase64File
  };
};

handleFile = async file => {
  const { originFile, base64file, originSize } = await getBase64File(file);
  const { width, height } = await getImageParams(base64file);
  const paddingTop = `${height / width * 100}%`;
  return { originFile, base64file, originSize, width, height, paddingTop };
};

handleCompressFile = async (file, compressRatio) => {
  const { base64file } = await getBase64File(file);
  const { width, height } = await getImageParams(base64file);
  const targetWidth = width * compressRatio;
  const targetHeight = height * compressRatio;
  // 创建Image 对象
  const image = new Image();
  image.src = base64file;
  // 创建画布
  // 创建画布
  const canvas = document.createElement("canvas");
  const context = canvas.getContext("2d");
  canvas.width = targetWidth;
  canvas.height = targetHeight;

  context.fillStyle = "rgba(255,255,255,1)";
  context.fillRect(0, 0, targetWidth, targetHeight);
  context.drawImage(image, 0, 0, targetWidth, targetHeight);
  const compressedBase64File = canvas.toDataURL("image/jpeg", compressRatio);
  return { compressedBase64File };
};

getBase64File = file =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    const result = {};
    reader.readAsDataURL(file);
    reader.onload = () => {
      result.base64file = reader.result;
      result.originFile = file;
      result.originSize = file.size;
      resolve(result);
    };
    reader.onerror = error => reject(error);
  });

getImageParams = base64file =>
  new Promise((resolve, reject) => {
    const image = new Image();
    image.src = base64file;
    image.onload = function() {
      const width = this.width;
      const height = this.height;
      resolve({ width, height });
    };
    image.onerror = error => reject(error);
  });

base64toBlob = (base64file, contentType = "image/jpg", sliceSize = 512) => {
  // 参考 https://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript
  const byteCharacters = atob(base64file.split(",")[1]);
  const byteArrays = [];
  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);
    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i += 1) {
      byteNumbers[i] = slice.charCodeAt(i);
    }
    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }
  return new Blob(byteArrays, { type: contentType });
};

$(function() {
  $("#file").on("change", async function(e) {
    const { compressedBase64File, base64file,originSize, compressSize, compressRate } = await handleChange(e);

    // 原始图片预览
    $(".origin").attr({
      src: base64file
    });
    // 压缩图片
    $(".compress").attr({
      src: compressedBase64File
    });

    // 信息展示
    $(".massage").html(`
          <div>原始图片大小:${originSize}k</div>
          <div>压缩图片大小:${compressSize}k</div>
          <div>压缩比:${compressRate}</div>
     `);
  });
});

              
            
!
999px

Console