用picturebox控件加载一个100M左右的图片 报溢出错误
代码呢
需要导入Drawing2D的命名空间
public void picCircle()
{
GraphicsPath gp = new GraphicsPath();
gp.AddEllipse(pictureBox1.ClientRectangle);
Region region = new Region(gp);
pictureBox1.Region = region;
gp.Dispose();
region.Dispose();
}
问题的核心在于PictureBox控件加载大尺寸照片时的溢出错误,解决方案可以采取以下步骤:
using (FileStream fs = new FileStream("path_to_your_photo.jpg", FileMode.Open))
{
pictureBox1.Image = Image.FromStream(fs);
}
using (Image originalImage = Image.FromFile("path_to_your_photo.jpg"))
{
int targetWidth = 800; // 设置目标宽度
int targetHeight = 600; // 设置目标高度
// 计算缩放比例
float scaleFactor = Math.Min((float)targetWidth / originalImage.Width, (float)targetHeight / originalImage.Height);
// 计算缩放后的尺寸
int scaledWidth = (int)(originalImage.Width * scaleFactor);
int scaledHeight = (int)(originalImage.Height * scaleFactor);
// 创建缩放后的图片
using (Bitmap scaledImage = new Bitmap(scaledWidth, scaledHeight))
{
using (Graphics graphics = Graphics.FromImage(scaledImage))
{
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; // 设置插值模式
graphics.DrawImage(originalImage, 0, 0, scaledWidth, scaledHeight); // 绘制缩放后的图片
}
pictureBox1.Image = scaledImage;
}
}
private async void LoadImageAsync(string filePath)
{
// 异步加载图片
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
pictureBox1.Image = await Task.Run(() => Image.FromStream(fs));
}
}
// 调用异步加载方法
LoadImageAsync("path_to_your_photo.jpg");
通过以上几个步骤,可以有效地解决C# PictureBox控件加载大尺寸照片时的溢出错误。如果还有其他问题,请提供更详细的信息和代码以便更好地指导解决方案。