Resizing an image in an HTML5 canvas

后端 未结 18 2670
半阙折子戏
半阙折子戏 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 03:43

    I'd highly suggest you check out this link and make sure it is set to true.

    Controlling image scaling behavior

    Introduced in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0)

    Gecko 1.9.2 introduced the mozImageSmoothingEnabled property to the canvas element; if this Boolean value is false, images won't be smoothed when scaled. This property is true by default. view plainprint?

    1. cx.mozImageSmoothingEnabled = false;
    0 讨论(0)
  • 2020-11-22 03:47

    Looking for another great simple solution?

    var img=document.createElement('img');
    img.src=canvas.toDataURL();
    $(img).css("background", backgroundColor);
    $(img).width(settings.width);
    $(img).height(settings.height);
    

    This solution will use the resize algorith of browser! :)

    0 讨论(0)
  • 2020-11-22 03:51

    I know this is an old thread but it might be useful for some people such as myself that months after are hitting this issue for the first time.

    Here is some code that resizes the image every time you reload the image. I am aware this is not optimal at all, but I provide it as a proof of concept.

    Also, sorry for using jQuery for simple selectors but I just feel too comfortable with the syntax.

    $(document).on('ready', createImage);
    $(window).on('resize', createImage);
    
    var createImage = function(){
      var canvas = document.getElementById('myCanvas');
      canvas.width = window.innerWidth || $(window).width();
      canvas.height = window.innerHeight || $(window).height();
      var ctx = canvas.getContext('2d');
      img = new Image();
      img.addEventListener('load', function () {
        ctx.drawImage(this, 0, 0, w, h);
      });
      img.src = 'http://www.ruinvalor.com/Telanor/images/original.jpg';
    };
    html, body{
      height: 100%;
      width: 100%;
      margin: 0;
      padding: 0;
      background: #000;
    }
    canvas{
      position: absolute;
      left: 0;
      top: 0;
      z-index: 0;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <html>
      <head>
        <meta charset="utf-8" />
        <title>Canvas Resize</title>
      </head>
      <body>
        <canvas id="myCanvas"></canvas>
      </body>
    </html>

    My createImage function is called once when the document is loaded and after that it is called every time the window receives a resize event.

    I tested it in Chrome 6 and Firefox 3.6, both on the Mac. This "technique" eats processor as it if was ice cream in the summer, but it does the trick.

    0 讨论(0)
  • 2020-11-22 03:53

    For resizing to image with width less that original, i use:

        function resize2(i) {
          var cc = document.createElement("canvas");
          cc.width = i.width / 2;
          cc.height = i.height / 2;
          var ctx = cc.getContext("2d");
          ctx.drawImage(i, 0, 0, cc.width, cc.height);
          return cc;
        }
        var cc = img;
        while (cc.width > 64 * 2) {
          cc = resize2(cc);
        }
        // .. than drawImage(cc, .... )
    

    and it works =).

    0 讨论(0)
  • 2020-11-22 03:53

    The problem with some of this solutions is that they access directly the pixel data and loop through it to perform the downsampling. Depending on the size of the image this can be very resource intensive, and it would be better to use the browser's internal algorithms.

    The drawImage() function is using a linear-interpolation, nearest-neighbor resampling method. That works well when you are not resizing down more than half the original size.

    If you loop to only resize max one half at a time, the results would be quite good, and much faster than accessing pixel data.

    This function downsample to half at a time until reaching the desired size:

      function resize_image( src, dst, type, quality ) {
         var tmp = new Image(),
             canvas, context, cW, cH;
    
         type = type || 'image/jpeg';
         quality = quality || 0.92;
    
         cW = src.naturalWidth;
         cH = src.naturalHeight;
    
         tmp.src = src.src;
         tmp.onload = function() {
    
            canvas = document.createElement( 'canvas' );
    
            cW /= 2;
            cH /= 2;
    
            if ( cW < src.width ) cW = src.width;
            if ( cH < src.height ) cH = src.height;
    
            canvas.width = cW;
            canvas.height = cH;
            context = canvas.getContext( '2d' );
            context.drawImage( tmp, 0, 0, cW, cH );
    
            dst.src = canvas.toDataURL( type, quality );
    
            if ( cW <= src.width || cH <= src.height )
               return;
    
            tmp.src = dst.src;
         }
    
      }
      // The images sent as parameters can be in the DOM or be image objects
      resize_image( $( '#original' )[0], $( '#smaller' )[0] );
    

    Credits to this post

    0 讨论(0)
  • 2020-11-22 03:54

    Fast and simple Javascript image resizer:

    https://github.com/calvintwr/blitz-hermite-resize

    const blitz = Blitz.create()
    
    /* Promise */
    blitz({
        source: DOM Image/DOM Canvas/jQuery/DataURL/File,
        width: 400,
        height: 600
    }).then(output => {
        // handle output
    })catch(error => {
        // handle error
    })
    
    /* Await */
    let resized = await blizt({...})
    
    /* Old school callback */
    const blitz = Blitz.create('callback')
    blitz({...}, function(output) {
        // run your callback.
    })
    

    History

    This is really after many rounds of research, reading and trying.

    The resizer algorithm uses @ViliusL's Hermite script (Hermite resizer is really the fastest and gives reasonably good output). Extended with features you need.

    Forks 1 worker to do the resizing so that it doesn't freeze your browser when resizing, unlike all other JS resizers out there.

    0 讨论(0)
提交回复
热议问题