Resizing an image in an HTML5 canvas

后端 未结 18 3116
半阙折子戏
半阙折子戏 2020-11-22 03:37

I\'m trying to create a thumbnail image on the client side using javascript and a canvas element, but when I shrink the image down, it looks terrible. It looks as if it was

18条回答
  •  清歌不尽
    2020-11-22 04:10

    I converted @syockit's answer as well as the step-down approach into a reusable Angular service for anyone who's interested: https://gist.github.com/fisch0920/37bac5e741eaec60e983

    I included both solutions because they both have their own pros / cons. The lanczos convolution approach is higher quality at the cost of being slower, whereas the step-wise downscaling approach produces reasonably antialiased results and is significantly faster.

    Example usage:

    angular.module('demo').controller('ExampleCtrl', function (imageService) {
      // EXAMPLE USAGE
      // NOTE: it's bad practice to access the DOM inside a controller, 
      // but this is just to show the example usage.
    
      // resize by lanczos-sinc filter
      imageService.resize($('#myimg')[0], 256, 256)
        .then(function (resizedImage) {
          // do something with resized image
        })
    
      // resize by stepping down image size in increments of 2x
      imageService.resizeStep($('#myimg')[0], 256, 256)
        .then(function (resizedImage) {
          // do something with resized image
        })
    })
    

提交回复
热议问题