是它的工作原理。調整圖像大小並將其顯示在按鈕上非常簡單。
但是,我不認爲上面的代碼保持圖像的縱橫比。
調整高寬比圖像非常簡單;然後在按鈕上顯示它。 以下示例代碼可幫助您通過保持高寬比來調整圖像大小。 您可以定義一個新類或在現有類中實施「ResizeImage」方法。無論你對誰舒服。
public class ImageManipulation
{
public static Bitmap ResizeImage(Bitmap originalBitmap, int newWidth, int maxHeight, bool onlyResizeIfWider)
{
if (onlyResizeIfWider)
{
if (originalBitmap.Width <= newWidth)
{
newWidth = originalBitmap.Width;
}
}
int newHeight = originalBitmap.Height * newWidth/originalBitmap.Width;
if (newHeight > maxHeight)
{
// Resize with height instead
newWidth = originalBitmap.Width * maxHeight/originalBitmap.Height;
newHeight = maxHeight;
}
var alteredImage = new Bitmap(originalBitmap, new Size(newWidth, newHeight));
alteredImage.SetResolution(72, 72);
return alteredImage;
}
}
用法:
private void DisplayPhoto()
{
// make sure the file is JPEG or GIF
System.IO.FileInfo testFile = new System.IO.FileInfo(myFile);
// Create a new stream to load this photo into
FileStream myFileStream = new FileStream(myFile, FileMode.Open, FileAccess.Read);
// Create a buffer to hold the stream of bytes
photo = new byte[myFileStream.Length];
// Read the bytes from this stream and put it into the image buffer
myStream.Read(photo, 0, (int)myFileStream.Length);
// Close the stream
myFileStream.Close();
// Create a new MemoryStream and write all the information from
// the byte array into the stream
MemoryStream myStream = new MemoryStream(photo, true);
myStream.Write(photo, 0, photo.Length);
// Use the MemoryStream to create the new BitMap object
Bitmap FinalImage = new Bitmap(myStream);
upicPhoto.Image = ImageManipulation.ResizeImage(
FinalImage,
upicPhoto.Width,
upicPhoto.Height,
true);
// Close the stream
myStream.Close();
}
我可能會加載圖像,調整其大小,丟棄原和使用調整之一。如果您仍然起訴相同的圖像,請嘗試將其緩存在某處 – Ondra
Ondra;這聽起來像一個優雅的解決方案你能告訴我如何處理原始圖像嗎?這甚至可能與.NET? –
MSRS比我快:)看到他的回答下面 – Ondra