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

发布于 2024-12-10 07:56:51 字数 302 浏览 2 评论 0原文

我有一些 JS 对图像进行一些操作。我想要类似像素艺术的图形,所以我必须在图形编辑器中放大原始图像。 但我认为用小图像进行所有操作然后使用 html5 功能放大它是个好主意。这将节省大量处理时间(因为现在我的演示警告:域名可能会导致工作中出现一些问题等)例如,在 Firefox 中加载时间非常长)。 但是当我尝试调整图像大小时,它会以双三次方式重新采样。如何使其在不重新采样的情况下调整图像大小?有没有跨浏览器的解决方案?

I have some JS that makes some manipulations with images. I want to have pixelart-like graphics, so I had to enlarge original images in graphics editor.
But I think it'd be good idea to make all the manipulations with the small image and then enlarge it with html5 functionality. This will save bunch of processing time (because now my demo (warning: domain-name may cause some issues at work etc) loads extremely long in Firefox, for example).
But when I try to resize the image, it gets resampled bicubically. How to make it resize image without resampling? Is there any crossbrowser solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

小耗子 2024-12-17 07:56:51
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 文档

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

http://phrogz.net/tmp/canvas_image_zoom.html can provide a fallback case using canvas and getImageData. In short:

// 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);
  }
}

More: MDN docs on image-rendering

云雾 2024-12-17 07:56:51

我不久前使用 ImageData 编写了一个 NN 调整大小脚本(大约第 1794 行)

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

您可以在此处查看演示

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

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

I wrote a NN resizing script a while ago using ImageData (around line 1794)

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

You can see a demo here

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

unfortunately the builtin resizing should be slightly faster.

孤单情人 2024-12-17 07:56:51

您只需设置 context.imageSmoothingEnabled< /a> 到 false。这将使使用 context.drawImage() 绘制的所有内容使用最近邻居调整大小。

// the canvas to resize
const canvas = document.createElement("canvas");

// the canvas to output to
const canvas2 = document.createElement("canvas");
const context2 = canvas2.getContext("2d");

// disable image smoothing
context2.imageSmoothingEnabled = false;

// draw image from the canvas
context2.drawImage(canvas, 0, 0, canvas2.width, canvas2.height);

这比使用有更好的支持图像渲染:像素化

You can simply set context.imageSmoothingEnabled to false. This will make everything drawn with context.drawImage() resize using nearest neighbor.

// the canvas to resize
const canvas = document.createElement("canvas");

// the canvas to output to
const canvas2 = document.createElement("canvas");
const context2 = canvas2.getContext("2d");

// disable image smoothing
context2.imageSmoothingEnabled = false;

// draw image from the canvas
context2.drawImage(canvas, 0, 0, canvas2.width, canvas2.height);

This has better support than using image-rendering: pixelated.

守不住的情 2024-12-17 07:56:51

canvas 元素上的此 CSS 有效:

image-rendering: pixelated;

截至 2021 年 9 月,这适用于 Chrome 93。

This CSS on the canvas element works:

image-rendering: pixelated;

This works in Chrome 93, as of September 2021.

夜光 2024-12-17 07:56:51

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

它使用 fillRect() 而不是循环遍历每个像素并绘制它。所有内容都带有注释,以帮助您更好地了解其工作原理。

//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;
}

下面是它的使用示例。

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

<img id="pixel-image" src="" data-src="pixel-image.png"/>

data-src 标记包含您要放大的图像的 URL。这是一个自定义数据标签。下面的代码将从数据标记中获取图像 URL,并将其通过调整大小函数,返回一个更大的图像(原始大小的 30 倍),然后将其注入到 src 属性中img 标签。

请记住,在包含以下内容之前,请将函数 Resize_Nearest_Neighbour(上面)放入

function Load_Image( element ){
    var source = element.getAttribute("data-src");
    var img = new Image();

    img.addEventListener("load", function(){

        var bigImage = Resize_Nearest_Neighbour( this, 30 );
        element.src = bigImage;

    });

    img.src = source;
}

Load_Image( document.getElementById("pixel-image") );

I'll echo what others have said and tell you it's not a built-in function. After running into the same issue, I've made one below.

It uses fillRect() instead of looping through each pixel and painting it. Everything is commented to help you better understand how it works.

//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;
}

Below is an example of it in use.

Your image would appear in the HTML like this:

<img id="pixel-image" src="" data-src="pixel-image.png"/>

The data-src tag contains the URL for the image you want to enlarge. This is a custom data tag. The code below will take the image URL from the data tag and put it through the resizing function, returning a larger image (30x the original size) which then gets injected into the src attribute of the img tag.

Remember to put the function Resize_Nearest_Neighbour (above) into the <script> tag before you include the following.

function Load_Image( element ){
    var source = element.getAttribute("data-src");
    var img = new Image();

    img.addEventListener("load", function(){

        var bigImage = Resize_Nearest_Neighbour( this, 30 );
        element.src = bigImage;

    });

    img.src = source;
}

Load_Image( document.getElementById("pixel-image") );
自此以后,行同陌路 2024-12-17 07:56:51

没有内置的方法。您必须使用 getImageData 自己完成此操作。

There is no built-in way. You have to do it yourself with getImageData.

心如狂蝶 2024-12-17 07:56:51

基于 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/

Based on Paul Irish's comment:

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/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文