嘗試縮放圖像時出現問題。當我想要縮放的圖像(原始圖像)小於我想要縮放的圖像時,問題就出現了。當原始圖像的高度和寬度較小時,圖像縮放不起作用縮放高度和寬度
例如,寬度爲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