Pen Settings

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

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <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>
            
          
!
            
              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;
  }
}
            
          
!
            
              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
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console