尝试缩放图像时出现问题。当我想要缩放的图像(原始图像)小于我想要缩放的图像时,问题就出现了。当原始图像的高度和宽度较小时,图像缩放不起作用缩放高度和宽度
例如,宽度为850px,高度为700px的图片尝试将宽度和高度放大到950px。图像似乎被正确缩放,但是在我的位图上画的是错误的。下面是缩放图像的代码。发送到ScaleToFitInside的宽度是尝试缩放到的宽度和高度,在我的示例中均为950px。
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;
}
所以画面被缩放,但beeing画错了我的位图从而导致影像“落”我在位图外,并没有展示其整体的自我。
示例:发送值为2000x2000(尝试升级)时。发生以下情况。
由于原始图片小于升幅值,我不想“诅咒它”,但要保持相同的大小。我想要的效果是绘制一个尺寸为2000x2000的矩形,并在其中心绘制图像。
我的示例图片会生成以下值:
width = 2000;高度= 2000; resized.Width将1000和resize.Height将737(原始图片大小)。
x =(2000-1000)/ 2 = 500; y =(2000 - 737)/ 2 = 631.
将这些值绘制到纸张上并将其与矩形匹配时,它似乎是正确的值,但图像仍然绘制在错误的位置上,而不是中间。
在此先感谢。
hmms,那是不对的。当我注销事件日志中的变量时,我得到以下结果。原始图像640x480。图片试图扩大到1250x1300,然后x = 305和y = 410所以这里没有负值。 – jinxen 2010-09-08 06:19:14
然后我不确定你传递了什么值:'(480 - 1300)/ 2 <0' – leppie 2010-09-08 06:34:08
在我的测试图片中,我发送的图片宽度为640,高度为480.如果图片小于尺寸的增大措施将保持不变。你的价值是错误的。第一个变量是试图增加或减小从web服务发送的beeing的值。 resized.Height是图片高度,在这种情况下,调整大小的图片将保持相同的大小。因此它将是(1250 - 640)/ 2和(1300 - 480)。 – jinxen 2010-09-08 07:04:33