Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

压缩图片分步缩小 #32

Open
hfc-advance opened this issue Oct 30, 2018 · 0 comments
Open

压缩图片分步缩小 #32

hfc-advance opened this issue Oct 30, 2018 · 0 comments
Labels

Comments

@hfc-advance
Copy link
Owner

hfc-advance commented Oct 30, 2018

使用 canvas 压缩图片

直接插入
原理是将图片插入按一定尺寸 canvas 然后再取出来,这样就完成了图片的压缩。

function resizeImage(img, width, height) {
    var canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    canvas.getContext('2d').drawImage(img, 0, 0, width, height);
    return canvas;
}

这种方法很简单,但是有个很大的缺陷。插入 canvas 时原理是是从几个点中取出一个点插入,这样造成了比较大的信息丢失。

优化

function resizeImage (image, targetWidth, targetHeight) {
  var steps = Math.ceil(Math.log2(image.width / targetWidth))
  if (steps < 1) {
    steps = 1
  }
  var sW = targetWidth * Math.pow(2, steps - 1)
  var sH = targetHeight * Math.pow(2, steps - 1)
  var x = 2

  while (steps--) {
    var canvas = document.createElement('canvas')
    canvas.width = sW
    canvas.height = sH
    canvas.getContext('2d').drawImage(image, 0, 0, sW, sH)
    image = canvas

    sW = Math.round(sW / x)
    sH = Math.round(sH / x)
  }

  return image
}

分步缩小,每次只将两个像素合成为一个像素。

在 ios 中, canvas 可能会限制加载图片大小,这个时候可以采取分配加载的方式进行处理

https://blog.uploadcare.com/image-resize-in-browsers-is-broken-e38eed08df01
https://github.com/transloadit/uppy/blob/bad0cfdd47163eb6ddf451c3c783489b8551f8fd/src/plugins/ThumbnailGenerator/index.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant