HTML5画布:有没有办法用“最近邻居”重新采样来调整图像大小?

时间:2011-10-18 14:57:53

标签: html5 canvas resampling

我有一些JS用图像进行一些操作。我想要像pixelart一样的图形,所以我不得不在图形编辑器中放大原始图像。 但我认为用小图像进行所有操作然后用html5功能放大它是个好主意。这将节省大量处理时间(因为现在my demo警告:域名可能会导致某些工作中的问题等)在Firefox中加载时间过长(例如)。 但是当我尝试调整图像大小时,它会被双重重采样。如何在不重新采样的情况下调整图像大小?有没有任何crossbrowser解决方案?

5 个答案:

答案 0 :(得分:12)

image-rendering: -webkit-optimize-contrast; /* webkit */
image-rendering: -moz-crisp-edges /* Firefox */

http://phrogz.net/tmp/canvas_image_zoom.html可以使用canvas和getImageData提供后备案例。简而言之:

// Create an offscreen canvas, draw an image to it, and fetch the pixels
var offtx = document.createElement('canvas').getContext('2d');
offtx.drawImage(img1,0,0);
var imgData = offtx.getImageData(0,0,img1.width,img1.height).data;

// Draw the zoomed-up pixels to a different canvas context
for (var x=0;x<img1.width;++x){
  for (var y=0;y<img1.height;++y){
    // Find the starting index in the one-dimensional image data
    var i = (y*img1.width + x)*4;
    var r = imgData[i  ];
    var g = imgData[i+1];
    var b = imgData[i+2];
    var a = imgData[i+3];
    ctx2.fillStyle = "rgba("+r+","+g+","+b+","+(a/255)+")";
    ctx2.fillRect(x*zoom,y*zoom,zoom,zoom);
  }
}

更多:MDN docs on image-rendering

答案 1 :(得分:3)

我前段时间使用ImageData(第1794行)

编写了一个NN大小调整脚本

https://github.com/arahaya/ImageFilters.js/blob/master/imagefilters.js

你可以在这里看到一个演示

http://www.arahaya.com/imagefilters/

不幸的是,内置调整大小应该稍快一些。

答案 2 :(得分:0)

没有内置方式。您必须自己使用getImageData

答案 3 :(得分:0)

我会回应其他人所说的话并告诉你它不是内置功能。在遇到同样的问题之后,我在下面做了一个。

它使用 fillRect()而不是循环遍历每个像素并绘制它。一切都被评论,以帮助您更好地了解它是如何工作的。

Declare @Text varchar(16) = '123.1234'

SELECT 
  CAST(@Text AS FLOAT) AS 'Float value'
, CAST(CAST(@Text AS Float) AS NVARCHAR(MAX)) AS 'float'
, CAST(CAST(@Text AS Float(4)) AS NVARCHAR(MAX)) AS 'float with precision'
, CAST(CAST(@Text AS numeric(8,4)) AS NVARCHAR(MAX)) AS 'numeric with precision'
, CAST(CAST(@Text AS decimal(8,4)) AS NVARCHAR(MAX)) AS 'decimal with precision'

下面是一个使用它的例子。

您的图片将显示在HTML中,如下所示:

//img is the original image, scale is a multiplier. It returns the resized image.
function Resize_Nearest_Neighbour( img, scale ){
    //make shortcuts for image width and height
    var w = img.width;
    var h = img.height;

    //---------------------------------------------------------------
    //draw the original image to a new canvas
    //---------------------------------------------------------------

    //set up the canvas
    var c = document.createElement("CANVAS");
    var ctx = c.getContext("2d");
    //disable antialiasing on the canvas
    ctx.imageSmoothingEnabled = false;
    //size the canvas to match the input image
    c.width = w;
    c.height = h;
    //draw the input image
    ctx.drawImage( img, 0, 0 );
    //get the input image as image data
    var inputImg = ctx.getImageData(0,0,w,h);
    //get the data array from the canvas image data
    var data = inputImg.data;

    //---------------------------------------------------------------
    //resize the canvas to our bigger output image
    //---------------------------------------------------------------
    c.width = w * scale;
    c.height = h * scale;
    //---------------------------------------------------------------
    //loop through all the data, painting each pixel larger
    //---------------------------------------------------------------
    for ( var i = 0; i < data.length; i+=4 ){

        //find the colour of this particular pixel
        var colour = "#";

        //---------------------------------------------------------------
        //convert the RGB numbers into a hex string. i.e. [255, 10, 100]
        //into "FF0A64"
        //---------------------------------------------------------------
        function _Dex_To_Hex( number ){
            var out = number.toString(16);
            if ( out.length < 2 ){
                out = "0" + out;
            }
            return out;
        }
        for ( var colourIndex = 0; colourIndex < 3; colourIndex++ ){
            colour += _Dex_To_Hex( data[ i+colourIndex ] );
        }
        //set the fill colour
        ctx.fillStyle = colour;

        //---------------------------------------------------------------
        //convert the index in the data array to x and y coordinates
        //---------------------------------------------------------------
        var index = i/4;
        var x = index % w;
        //~~ is a faster way to do 'Math.floor'
        var y = ~~( index / w );
        //---------------------------------------------------------------
        //draw an enlarged rectangle on the enlarged canvas
        //---------------------------------------------------------------
        ctx.fillRect( x*scale, y*scale, scale, scale );
    }

    //get the output image from the canvas
    var output = c.toDataURL("image/png");
    //returns image data that can be plugged into an img tag's src
    return output;
}

<img id="pixel-image" src="" data-src="pixel-image.png"/> 标记包含您要放大的图片的网址。这是一个自定义数据标记。下面的代码将从数据标记中获取图像URL并将其放入调整大小函数,返回一个较大的图像(原始大小的30倍),然后将其注入data-src标记的src属性中

在包含以下内容之前,请务必将img(上方)功能放入Resize_Nearest_Neighbour标记。

<script>

答案 4 :(得分:-1)

基于Paul Irish的评论:

function resizeBase64(base64, zoom) {
    return new Promise(function(resolve, reject) {
        var img = document.createElement("img");

        // once image loaded, resize it
        img.onload = function() {
            // get image size
            var imageWidth = img.width;
            var imageHeight = img.height;

            // create and draw image to our first offscreen canvas
            var canvas1 = document.createElement("canvas");
            canvas1.width = imageWidth;
            canvas1.height = imageHeight;
            var ctx1 = canvas1.getContext("2d");
            ctx1.drawImage(this, 0, 0, imageWidth, imageHeight);

            // get pixel data from first canvas
            var imgData = ctx1.getImageData(0, 0, imageWidth, imageHeight).data;

            // create second offscreen canvas at the zoomed size
            var canvas2 = document.createElement("canvas");
            canvas2.width = imageWidth * zoom;
            canvas2.height = imageHeight * zoom;
            var ctx2 = canvas2.getContext("2d");

            // draw the zoomed-up pixels to a the second canvas
            for (var x = 0; x < imageWidth; ++x) {
                for (var y = 0; y < imageHeight; ++y) {
                    // find the starting index in the one-dimensional image data
                    var i = (y * imageWidth + x) * 4;
                    var r = imgData[i];
                    var g = imgData[i + 1];
                    var b = imgData[i + 2];
                    var a = imgData[i + 3];
                    ctx2.fillStyle = "rgba(" + r + "," + g + "," + b + "," + a / 255 + ")";
                    ctx2.fillRect(x * zoom, y * zoom, zoom, zoom);
                }
            }

            // resolve promise with the zoomed base64 image data
            var dataURI = canvas2.toDataURL();
            resolve(dataURI);
        };
        img.onerror = function(error) {
            reject(error);
        };
        // set the img soruce
        img.src = base64;
    });
}

resizeBase64(src, 4).then(function(zoomedSrc) {
    console.log(zoomedSrc);
});

https://jsfiddle.net/djhyquon/69/