计算机如何调整图像大小



图像大小调整在任何GUI框架中几乎都是通用的。事实上,在开始web开发时,您首先要学习的一件事是如何使用CSS或HTML的img属性缩放图像。但这是怎么回事呢?

当我告诉计算机将500x500 img缩放到100x50时,或者反过来,计算机如何知道从原始图像中绘制哪些像素?最后,对我来说,用另一种编程语言编写自己的"图像转换器"是否相当容易,而不会显著降低性能?

根据一些研究,我可以得出结论,大多数web浏览器都会使用最近邻居或线性插值来调整图像大小。我写了一个概念最近邻算法,它成功地调整了图像的大小,尽管速度很慢。

using System;
using System.Drawing;
using System.Timers;
namespace Image_Resize
{
class ImageResizer
{
public static Image Resize(Image baseImage, int newHeight, int newWidth)
{
var baseBitmap = new Bitmap(baseImage);
int baseHeight = baseBitmap.Height;
int baseWidth = baseBitmap.Width;
//Nearest neighbor interpolation converts pixels in the resized image to pixels closest to the old image. We have a 2x2 image, and want to make it a 9x9.
//Step 1. Take a 9x9 image and shrink it back to old value. To do this, divide the new width by old width (i.e. 9/2 = 4.5)
float widthRatio = (float)baseWidth/newWidth;
float heightRatio = (float)baseHeight/newHeight;
//Step 2. Perform an integer comparison for each pixel in old I believe. If we have a pixel in the new located at (4,5), then the proportional will be
//(.8888, 1.11111) which SHOULD GO DOWN to (0,1) coordinates on a 2x2. Seems counter intuitive, but imagining a 2x2 grid, (4.5) is on the left-bottom coordinate
//so it makes sense the to be on the (0,1) pixel.

var watch = new System.Diagnostics.Stopwatch();
watch.Start();
Bitmap resized = new Bitmap(newWidth, newHeight);
int oldX = 0; int oldY = 0;
for (int i = 0; i < newWidth; i++)
{
oldX = (int)(i*widthRatio);
for (int j = 0; j < newHeight; j++)
{
oldY = (int)(j*heightRatio);
Color newColor = baseBitmap.GetPixel(oldX,oldY);
resized.SetPixel(i,j, newColor);
}
}
//This works, but is 100x slower than standard library methods due to GetPixel() and SetPixel() methods. The average time to set a 1920x1080 image is a second.
watch.Stop();
Console.WriteLine("Resizing the image took " + watch.Elapsed.TotalMilliseconds + "ms.");
return resized;
}
}
class Program
{
static void Main(string[] args)
{
var img = Image.FromFile(@"C:UserskpsinPicturescodeimage.jpg");
img = ImageResizer.Resize(img, 1000, 1500);
img.Save(@"C:UserskpsinPicturescodeimage1.jpg");
}
}
}

我真的希望其他人能来提供a(一个更快的算法给最近的邻居,因为我忽略了一些愚蠢的东西,或者b(另一种我不知道的图像缩放器的工作方式。否则,问题。。。回答了吗?

最新更新