如何调整图像的大小 C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1922040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to resize an Image C#
提问by inutan
As Size
, Width
and Height
are Get()
properties of System.Drawing.Image
;
How can I resize an Image object at run-time in C#?
As Size
,Width
和Height
是 的Get()
属性System.Drawing.Image
;
如何在运行时在 C# 中调整 Image 对象的大小?
Right now, I am just creating a new Image
using:
现在,我只是创建一个新的Image
使用:
// objImage is the original Image
Bitmap objBitmap = new Bitmap(objImage, new Size(227, 171));
回答by Vinzz
in this question, you'll have some answers, including mine:
在这个问题中,你会得到一些答案,包括我的:
public Image resizeImage(int newWidth, int newHeight, string stPhotoPath)
{
Image imgPhoto = Image.FromFile(stPhotoPath);
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
//Consider vertical pics
if (sourceWidth < sourceHeight)
{
int buff = newWidth;
newWidth = newHeight;
newHeight = buff;
}
int sourceX = 0, sourceY = 0, destX = 0, destY = 0;
float nPercent = 0, nPercentW = 0, nPercentH = 0;
nPercentW = ((float)newWidth / (float)sourceWidth);
nPercentH = ((float)newHeight / (float)sourceHeight);
if (nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = System.Convert.ToInt16((newWidth -
(sourceWidth * nPercent)) / 2);
}
else
{
nPercent = nPercentW;
destY = System.Convert.ToInt16((newHeight -
(sourceHeight * nPercent)) / 2);
}
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap bmPhoto = new Bitmap(newWidth, newHeight,
PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.Clear(Color.Black);
grPhoto.InterpolationMode =
System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
imgPhoto.Dispose();
return bmPhoto;
}
回答by Dominic
This will -
这会 -
- Resize width AND height without the need for a loop
- Doesn't exceed the images original dimensions
- 无需循环即可调整宽度和高度
- 不超过图片原始尺寸
//////////////
/////////////
private void ResizeImage(Image img, double maxWidth, double maxHeight)
{
double resizeWidth = img.Source.Width;
double resizeHeight = img.Source.Height;
double aspect = resizeWidth / resizeHeight;
if (resizeWidth > maxWidth)
{
resizeWidth = maxWidth;
resizeHeight = resizeWidth / aspect;
}
if (resizeHeight > maxHeight)
{
aspect = resizeWidth / resizeHeight;
resizeHeight = maxHeight;
resizeWidth = resizeHeight * aspect;
}
img.Width = resizeWidth;
img.Height = resizeHeight;
}
回答by Leslie Marshall
This is the code that I worked out for a specific requirement ie: the destination is always in landscape ratio. It should give you a good start.
这是我针对特定要求制定的代码,即:目的地始终处于横向比例。它应该给你一个良好的开端。
public Image ResizeImage(Image source, RectangleF destinationBounds)
{
RectangleF sourceBounds = new RectangleF(0.0f,0.0f,(float)source.Width, (float)source.Height);
RectangleF scaleBounds = new RectangleF();
Image destinationImage = new Bitmap((int)destinationBounds.Width, (int)destinationBounds.Height);
Graphics graph = Graphics.FromImage(destinationImage);
graph.InterpolationMode =
System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
// Fill with background color
graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), destinationBounds);
float resizeRatio, sourceRatio;
float scaleWidth, scaleHeight;
sourceRatio = (float)source.Width / (float)source.Height;
if (sourceRatio >= 1.0f)
{
//landscape
resizeRatio = destinationBounds.Width / sourceBounds.Width;
scaleWidth = destinationBounds.Width;
scaleHeight = sourceBounds.Height * resizeRatio;
float trimValue = destinationBounds.Height - scaleHeight;
graph.DrawImage(source, 0, (trimValue / 2), destinationBounds.Width, scaleHeight);
}
else
{
//portrait
resizeRatio = destinationBounds.Height/sourceBounds.Height;
scaleWidth = sourceBounds.Width * resizeRatio;
scaleHeight = destinationBounds.Height;
float trimValue = destinationBounds.Width - scaleWidth;
graph.DrawImage(source, (trimValue / 2), 0, scaleWidth, destinationBounds.Height);
}
return destinationImage;
}
回答by Quispie
In the application I made it was necessary to create a function with multiple options. It's quite large, but it resizes the image, can keep the aspect ratio and can cut of the edges to return only the center of the image:
在我制作的应用程序中,有必要创建一个具有多个选项的函数。它相当大,但它可以调整图像大小,可以保持纵横比并且可以切割边缘以仅返回图像的中心:
/// <summary>
/// Resize image with a directory as source
/// </summary>
/// <param name="OriginalFileLocation">Image location</param>
/// <param name="heigth">new height</param>
/// <param name="width">new width</param>
/// <param name="keepAspectRatio">keep the aspect ratio</param>
/// <param name="getCenter">return the center bit of the image</param>
/// <returns>image with new dimentions</returns>
public Image resizeImageFromFile(String OriginalFileLocation, int heigth, int width, Boolean keepAspectRatio, Boolean getCenter)
{
int newheigth = heigth;
System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFileLocation);
// Prevent using images internal thumbnail
FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
if (keepAspectRatio || getCenter)
{
int bmpY = 0;
double resize = (double)FullsizeImage.Width / (double)width;//get the resize vector
if (getCenter)
{
bmpY = (int)((FullsizeImage.Height - (heigth * resize)) / 2);// gives the Y value of the part that will be cut off, to show only the part in the center
Rectangle section = new Rectangle(new Point(0, bmpY), new Size(FullsizeImage.Width, (int)(heigth * resize)));// create the section to cut of the original image
//System.Console.WriteLine("the section that will be cut off: " + section.Size.ToString() + " the Y value is minimized by: " + bmpY);
Bitmap orImg = new Bitmap((Bitmap)FullsizeImage);//for the correct effect convert image to bitmap.
FullsizeImage.Dispose();//clear the original image
using (Bitmap tempImg = new Bitmap(section.Width, section.Height))
{
Graphics cutImg = Graphics.FromImage(tempImg);// set the file to save the new image to.
cutImg.DrawImage(orImg, 0, 0, section, GraphicsUnit.Pixel);// cut the image and save it to tempImg
FullsizeImage = tempImg;//save the tempImg as FullsizeImage for resizing later
orImg.Dispose();
cutImg.Dispose();
return FullsizeImage.GetThumbnailImage(width, heigth, null, IntPtr.Zero);
}
}
else newheigth = (int)(FullsizeImage.Height / resize);// set the new heigth of the current image
}//return the image resized to the given heigth and width
return FullsizeImage.GetThumbnailImage(width, newheigth, null, IntPtr.Zero);
}
To make it easier to acces the function it's possible to add some overloaded functions:
为了更容易访问该函数,可以添加一些重载函数:
/// <summary>
/// Resize image with a directory as source
/// </summary>
/// <param name="OriginalFileLocation">Image location</param>
/// <param name="heigth">new height</param>
/// <param name="width">new width</param>
/// <returns>image with new dimentions</returns>
public Image resizeImageFromFile(String OriginalFileLocation, int heigth, int width)
{
return resizeImageFromFile(OriginalFileLocation, heigth, width, false, false);
}
/// <summary>
/// Resize image with a directory as source
/// </summary>
/// <param name="OriginalFileLocation">Image location</param>
/// <param name="heigth">new height</param>
/// <param name="width">new width</param>
/// <param name="keepAspectRatio">keep the aspect ratio</param>
/// <returns>image with new dimentions</returns>
public Image resizeImageFromFile(String OriginalFileLocation, int heigth, int width, Boolean keepAspectRatio)
{
return resizeImageFromFile(OriginalFileLocation, heigth, width, keepAspectRatio, false);
}
Now are the last two booleans optional to set. Call the function like this:
现在是最后两个可选设置的布尔值。像这样调用函数:
System.Drawing.Image ResizedImage = resizeImageFromFile(imageLocation, 800, 400, true, true);
回答by Matt
Not sure what is so difficult about this, do what you were doing, use the overloaded Bitmap constructor to create a re-sized image, the only thing you were missing was a cast back to the Image data type:
不确定这有什么困难,做你正在做的事情,使用重载的 Bitmap 构造函数来创建一个重新调整大小的图像,你唯一缺少的是转换回 Image 数据类型:
public static Image resizeImage(Image imgToResize, Size size)
{
return (Image)(new Bitmap(imgToResize, size));
}
yourImage = resizeImage(yourImage, new Size(50,50));
回答by Lino Silva
Why not use the System.Drawing.Image.GetThumbnailImage
method?
为什么不使用该System.Drawing.Image.GetThumbnailImage
方法?
public Image GetThumbnailImage(
int thumbWidth,
int thumbHeight,
Image.GetThumbnailImageAbort callback,
IntPtr callbackData)
Example:
例子:
Image originalImage = System.Drawing.Image.FromStream(inputStream, true, true);
Image resizedImage = originalImage.GetThumbnailImage(newWidth, (newWidth * originalImage.Height) / originalWidth, null, IntPtr.Zero);
resizedImage.Save(imagePath, ImageFormat.Png);
Source: http://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage.aspx
来源:http: //msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage.aspx
回答by mpen
This will perform a high quality resize:
这将执行高质量的调整大小:
/// <summary>
/// Resize the image to the specified width and height.
/// </summary>
/// <param name="image">The image to resize.</param>
/// <param name="width">The width to resize to.</param>
/// <param name="height">The height to resize to.</param>
/// <returns>The resized image.</returns>
public static Bitmap ResizeImage(Image image, int width, int height)
{
var destRect = new Rectangle(0, 0, width, height);
var destImage = new Bitmap(width, height);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(destImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width,image.Height, GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
wrapMode.SetWrapMode(WrapMode.TileFlipXY)
prevents ghosting around the image borders -- na?ve resizing will sample transparent pixels beyond the image boundaries, but by mirroring the image we can get a better sample (this setting is very noticeable)destImage.SetResolution
maintains DPI regardless of physical size -- may increase quality when reducing image dimensions or when printing- Compositing controls how pixels are blended with the background -- might not be needed since we're only drawing one thing.
graphics.CompositingMode
determines whether pixels from a source image overwrite or are combined with background pixels.SourceCopy
specifies that when a color is rendered, it overwrites the background color.graphics.CompositingQuality
determines the rendering quality level of layered images.
graphics.InterpolationMode
determines how intermediate values between two endpoints are calculatedgraphics.SmoothingMode
specifies whether lines, curves, and the edges of filled areas use smoothing (also called antialiasing) -- probably only works on vectorsgraphics.PixelOffsetMode
affects rendering quality when drawing the new image
wrapMode.SetWrapMode(WrapMode.TileFlipXY)
防止图像边界周围出现重影——天真的调整大小将采样超出图像边界的透明像素,但通过镜像图像我们可以获得更好的样本(这个设置非常明显)destImage.SetResolution
无论物理尺寸如何,都保持 DPI -- 在缩小图像尺寸或打印时可能会提高质量- 合成控制像素与背景的混合方式——可能不需要,因为我们只绘制一件事。
graphics.CompositingMode
确定来自源图像的像素是覆盖还是与背景像素组合。SourceCopy
指定在呈现颜色时,它会覆盖背景颜色。graphics.CompositingQuality
确定分层图像的渲染质量级别。
graphics.InterpolationMode
确定如何计算两个端点之间的中间值graphics.SmoothingMode
指定直线、曲线和填充区域的边缘是否使用平滑(也称为抗锯齿)——可能仅适用于向量graphics.PixelOffsetMode
绘制新图像时影响渲染质量
Maintaining aspect ratio is left as an exercise for the reader (actually, I just don't think it's this function's job to do that for you).
保持纵横比留给读者作为练习(实际上,我只是不认为这个功能的工作是为你做这件事)。
Also, this is a good articledescribing some of the pitfalls with image resizing. The above function will cover most of them, but you still have to worry about saving.
此外,这是一篇很好的文章,描述了图像调整大小的一些陷阱。上面的函数会覆盖大部分,但是你仍然需要担心保存.
回答by bhupendra singh
public string CreateThumbnail(int maxWidth, int maxHeight, string path)
{
var image = System.Drawing.Image.FromFile(path);
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
Graphics thumbGraph = Graphics.FromImage(newImage);
thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
//thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
thumbGraph.DrawImage(image, 0, 0, newWidth, newHeight);
image.Dispose();
string fileRelativePath = "newsizeimages/" + maxWidth + Path.GetFileName(path);
newImage.Save(Server.MapPath(fileRelativePath), newImage.RawFormat);
return fileRelativePath;
}
Click here http://bhupendrasinghsaini.blogspot.in/2014/07/resize-image-in-c.html
点击这里http://bhupendrasinghsaini.blogspot.in/2014/07/resize-image-in-c.html
回答by NeoSvet
public static Image resizeImage(Image image, int new_height, int new_width)
{
Bitmap new_image = new Bitmap(new_width, new_height);
Graphics g = Graphics.FromImage((Image)new_image );
g.InterpolationMode = InterpolationMode.High;
g.DrawImage(image, 0, 0, new_width, new_height);
return new_image;
}
回答by Mateen Ulhaq
If you're working with a BitmapSource
:
如果您正在使用BitmapSource
:
var resizedBitmap = new TransformedBitmap(
bitmapSource,
new ScaleTransform(scaleX, scaleY));
If you want finer control over quality, run this first:
如果您想更好地控制质量,请先运行:
RenderOptions.SetBitmapScalingMode(
bitmapSource,
BitmapScalingMode.HighQuality);
(Default is BitmapScalingMode.Linear
which is equivalent to BitmapScalingMode.LowQuality
.)
(默认值BitmapScalingMode.Linear
相当于BitmapScalingMode.LowQuality
。)