gpt4 book ai didi

c# - 如何调整不同分辨率的图像大小

转载 作者:太空宇宙 更新时间:2023-11-03 11:01:46 26 4
gpt4 key购买 nike

我必须在照片库中显示图像@width=200 height=180,但是在上传图像时我必须调整它的大小,但问题是每张图像都有不同的分辨率。如何调整具有不同分辨率的图像的大小,以使图像保持完整。这是我的代码:

private void ResizeImage()
{
System.Drawing.Image ImageToUpload = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
byte[] image = null;
int h = ImageToUpload.Height;
int w = ImageToUpload.Width;
int r = int.Parse(ImageToUpload.VerticalResolution.ToString());
int NewWidth = 200;//constant
int NewHeight = 180;//constant
byte[] imagesize = FileUpload1.FileBytes;
System.Drawing.Bitmap BitMapImage = new System.Drawing.Bitmap(ImageToUpload, NewWidth, NewHeight);//this line gives horrible output
MemoryStream Memory = new MemoryStream();
BitMapImage.Save(Memory, System.Drawing.Imaging.ImageFormat.Jpeg);
Memory.Position = 0;
image = new byte[Memory.Length + 1];
Memory.Read(image, 0, image.Length);
}

如果分辨率是 96 并且如果我设置 maxwidth=200 那么它的高度将是 150 然后只有图像看起来小而准确。我们不能以所需的方式调整图像大小以使其看起来准确吗?

最佳答案

该函数将调整图像的大小以保持宽高比。

public static Image Resize(Image originalImage, int w, int h)
{
//Original Image attributes
int originalWidth = originalImage.Width;
int originalHeight = originalImage.Height;

// Figure out the ratio
double ratioX = (double)w / (double)originalWidth;
double ratioY = (double)h / (double)originalHeight;
// use whichever multiplier is smaller
double ratio = ratioX < ratioY ? ratioX : ratioY;

// now we can get the new height and width
int newHeight = Convert.ToInt32(originalHeight * ratio);
int newWidth = Convert.ToInt32(originalWidth * ratio);

Image thumbnail = new Bitmap(newWidth, newHeight);
Graphics graphic = Graphics.FromImage(thumbnail);

graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = SmoothingMode.HighQuality;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphic.CompositingQuality = CompositingQuality.HighQuality;

graphic.Clear(Color.Transparent);
graphic.DrawImage(originalImage, 0, 0, newWidth, newHeight);

return thumbnail;
}

用法

Image BitMapImage = Resize(ImageToUpload, NewWidth, NewHeight);

关于c# - 如何调整不同分辨率的图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17441098/

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