Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. function compress(img) {
  2. var initSize = img.src.length;
  3. var width = img.width;
  4. var height = img.height;
  5.  
  6. //如果图片大于四百万像素,计算压缩比并将大小压至400万以下
  7. var ratio;
  8. if ((ratio = width * height / 4000000)>1) {
  9. ratio = Math.sqrt(ratio);
  10. width /= ratio;
  11. height /= ratio;
  12. }else {
  13. ratio = 1;
  14. }
  15.  
  16. canvas.width = width;
  17. canvas.height = height;
  18.  
  19. // 铺底色
  20. ctx.fillStyle = "#fff";
  21. ctx.fillRect(0, 0, canvas.width, canvas.height);
  22.  
  23. //如果图片像素大于100万则使用瓦片绘制
  24. var count;
  25. if ((count = width * height / 1000000) > 1) {
  26. count = ~~(Math.sqrt(count)+1); //计算要分成多少块瓦片
  27.  
  28. // 计算每块瓦片的宽和高
  29. var nw = ~~(width / count);
  30. var nh = ~~(height / count);
  31.  
  32. tCanvas.width = nw;
  33. tCanvas.height = nh;
  34.  
  35. for (var i = 0; i < count; i++) {
  36. for (var j = 0; j < count; j++) {
  37. tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
  38.  
  39. ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
  40. }
  41. }
  42. } else {
  43. ctx.drawImage(img, 0, 0, width, height);
  44. }
  45.  
  46. //进行最小压缩
  47. var ndata = canvas.toDataURL('image/jpeg', 0.1);
  48.  
  49. console.log('压缩前:' + initSize);
  50. console.log('压缩后:' + ndata.length);
  51. console.log('压缩率:' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
  52.  
  53. tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
  54.  
  55. return ndata;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement