gpt4 book ai didi

html - 计算机如何调整图像的大小?

转载 作者:行者123 更新时间:2023-12-05 07:09:41 26 4
gpt4 key购买 nike

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

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

最佳答案

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

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:\Users\kpsin\Pictures\codeimage.jpg");
img = ImageResizer.Resize(img, 1000, 1500);
img.Save(@"C:\Users\kpsin\Pictures\codeimage1.jpg");
}
}
}

我确实希望其他人可以提供 a) 更快的最近邻算法,因为我忽略了一些愚蠢的事情,或者 b) 我不知道的图像缩放器的另一种工作方式。否则,问题...回答了吗?

关于html - 计算机如何调整图像的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61471140/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com