我正在使用.net4.5,Windows表单和C#。
我使用以下方式将图像加载到按钮上:
theButton.BackgroundImage = Image.FromFile("file.png");
问题是我的按钮是128x128,图像为4000x8000。上面的线会消耗大量内存,因为file.png太大。
有人知道我可以用来减少这种记忆足迹的技术吗?我正在考虑这样的功能:
Image.FromFile(file,width,height);
有指针吗?谢谢。
是的。调整图像大小然后在按钮上显示非常简单。
但是,我认为上面的代码不维护图像的纵横比。
以纵横比调整图像的大小非常简单。然后在按钮上显示它。以下是示例代码通过维护纵横比来帮助您调整图像大小。您可以在现有类中定义新类或实现" 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();
}
我认为您最好的路径就是将图像大小调整到128x128。无论您如何处理,大图总是会占用很多记忆。
这还可以使您可以使图像看起来像该大小一样好。
这是一个普遍的问题,afaik您几乎没有可能性
- 在上传前压缩图像,在现实世界中,这将行不通。
- 对图像的尺寸和尺寸进行检查,在现实世界中,它有效,甚至是LinkedIn,Facebook,他们不允许我们上传图像上方指定的维度。
- 使用缓冲,这是您可以在.NET中做的最干净的方法
- 使用一些第三方插件或开发环境,我已经在Silverlight 进行了