【发布时间】:2011-04-09 05:31:18
【问题描述】:
我在尝试缩放图像时遇到问题。当我尝试缩放的图像(原始)小于我尝试缩放的尺寸时,问题就会出现。
例如,一个宽度为 850 像素、高度为 700 像素的图像试图放大到 950 像素的宽度和高度。图像似乎已正确缩放,但在我的位图上绘制错误。接下来是缩放图像的代码。发送到 ScaleToFitInside 的宽度是尝试缩放到的宽度和高度,在我的示例中均为 950 像素。
public static Image ScaleToFitInside(Image image, int width, int height) {
Image reszied = ScaleToFit(image, width, height);
Bitmap bitmap = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bitmap)) {
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
Rectangle rect = new Rectangle(0, 0, width, height);
g.FillRectangle(Brushes.White, rect);
int x = (int)(((float)width - (float)reszied.Width) / 2);
int y = (int)(((float)height - (float)reszied.Height) / 2);
Point p = new Point(x, y);
g.DrawImageUnscaled(reszied, p);
foreach (PropertyItem item in image.PropertyItems) {
bitmap.SetPropertyItem(item);
}
}
return bitmap;
}
public static Image ScaleToFit(Image image, int maxWidth, int maxHeight) {
int width = image.Width;
int height = image.Height;
float scale = Math.Min(
((float)maxWidth / (float)width),
((float)maxHeight / (float)height));
return (scale < 1) ? Resize(image, (int)(width * scale), (int)(height * scale)) : image;
}
public static Image Resize(Image image, int width, int height) {
Bitmap bitmap = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bitmap)) {
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
Rectangle rect = new Rectangle(0, 0, width, height);
g.DrawImage(image, rect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
foreach (PropertyItem item in image.PropertyItems) {
bitmap.SetPropertyItem(item);
}
}
return bitmap;
}
所以图片被缩放,但是在我的位图上绘制错误导致图像“落”在我的位图之外并且没有呈现它的整体。
示例:发送 2000x2000 值时(尝试放大)。会发生以下情况。
由于原始图片小于升迁值,我不想“将其保存起来”,而是保持相同的大小。我想要的效果是绘制一个大小为 2000x2000 的矩形并在其中心绘制图像。
我的示例图片产生这些值:
宽度 = 2000;高度 = 2000; resized.Width 为 1000,resized.Height 为 737(原始图片大小)。
x = (2000 - 1000) / 2 = 500; y = (2000 - 737) / 2 = 631。
将这些值绘制到纸上并将其与矩形匹配时,它似乎是正确的值,但图像仍然绘制在错误的位置,而不是在中间。
提前致谢。
【问题讨论】:
标签: c# asp.net image-processing image-manipulation