2012-01-22 122 views
1

我一直在試圖改變我的照片的大小。我看了很多網站:12,3Winforms清除位圖圖像?

最後一個鏈接(3)至少會調整圖像的大小,除了舊圖像保留在調整後的圖像之外。這是怎麼發生的?爲什麼?如果我將winform最小化,然後將winform備份起來,則舊圖像消失了,剩下的只是調整後的版本。我如何擺脫舊的形象?

任何想法?

+0

你的調整大小的方法沒有任何問題。 – doogle

+2

*從不*使用CreateGraphics(),它不會正確地清除背景,並且您繪製的任何內容都將很容易消失。實施Paint事件,並使用傳遞的e.Graphics。您的Click事件應調用Invalidate()來觸發繪畫。 –

+0

也許你可以發佈代碼示例,以便我們可以看到你在做什麼。 –

回答

1

C# Tutorial - Image Editing: Saving, Cropping, and Resizing的第一個鏈接給你的代碼。

有沒有理由不使用它?

private static Image resizeImage(Image imgToResize, Size size) 
{ 
    int sourceWidth = imgToResize.Width; 
    int sourceHeight = imgToResize.Height; 

    float nPercent = 0; 
    float nPercentW = 0; 
    float nPercentH = 0; 

    nPercentW = ((float)size.Width/(float)sourceWidth); 
    nPercentH = ((float)size.Height/(float)sourceHeight); 

    if (nPercentH < nPercentW) 
     nPercent = nPercentH; 
    else 
     nPercent = nPercentW; 

    int destWidth = (int)(sourceWidth * nPercent); 
    int destHeight = (int)(sourceHeight * nPercent); 

    Bitmap b = new Bitmap(destWidth, destHeight); 
    Graphics g = Graphics.FromImage((Image)b); 
    g.InterpolationMode = InterpolationMode.HighQualityBicubic; 

    g.DrawImage(imgToResize, 0, 0, destWidth, destHeight); 
    g.Dispose(); 

    return (Image)b; 
} 

不要忽視InterpolationMode。它會使圖像更好看。

此外,我不認爲你想在這種情況下使用CreateGraphics()。您可能想要使用實際位圖來存儲調整大小的圖像,或者僅使用要顯示圖像的控件的繪製事件中的對象Graphic

+0

我已經嘗試將其添加到我的代碼中,但它不會工作,我不得不確保StartPainting獲取返回的圖像(如果我這樣做,它編譯並運行沒有錯誤,但圖像不會更改大小?(不知道爲什麼)..... – BigBug

+0

@BlueMonster你的原始圖像是什麼?它看起來像你試圖從控件調整圖像大小,而不是原始位圖。 – LarsTech

+0

我有一個圖像使用OpenFileDialog ...我玩的位來改變它的顏色等我使用位圖...玩顏色我必須鎖定圖像到內存然後我解鎖使用「UnlockBits()」,似乎都是工作正常......它只是調整大小,我不知道如何去玩比賽來調整我的形象? – BigBug