C#使用picutreBox循环显示大尺寸图像时会出现断层,显示不完整
最近的一个项目,需要用C#视频抠图,把扣好视频每一帧的图在前端显示,最近增加了更换背景的功能,最初使用picutreBox.BackgroundImage实现,发现如果背景图片过大的话会出现图片断层的现象,然后考虑把背景用单独的控件显示,结果发现picutreBox控件的透明背景其实是把父控件的背景在自己身上重绘出来,相当于盖章,尝试自定义picutreBox控件重写OnPaintBackground方法不执行任何操作
protected override void OnPaintBackground(PaintEventArgs pevent)
{
//do nothing
}
protected override void OnMove(EventArgs e)
{
RecreateHandle();
}
// Override the CreateParams property:
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle = 0x00000020; //WS_EX_TRANSPARENT
return cp;
}
}
结果背景纯黑色
尝试关闭重绘
public Test_PictureBox()
{
this.Width = 100;
this.Height = 100;
SetTransparenz();
}
private void SetTransparenz()
{
this.SetStyle(System.Windows.Forms.ControlStyles.Opaque, true);
this.SetStyle(System.Windows.Forms.ControlStyles.OptimizedDoubleBuffer, false);
this.SetStyle(System.Windows.Forms.ControlStyles.ResizeRedraw, true);
}
protected override System.Windows.Forms.CreateParams CreateParams
{
get
{
System.Windows.Forms.CreateParams cp = base.CreateParams;
cp.ExStyle = cp.ExStyle | 0x20;
// Turn on WS_EX_TRANSPARENTreturn cp;
}
}
结果是运行时出现重影
想要有一个方案可以解决这个问题
环境不同,仅供参考【图片太大导致 imageView无法显示】:https://blog.csdn.net/Demon_xiaochunjie/article/details/79424777
picutreBox有image属性,你应该修改它的前景图片而不是背景图片
如果你要重绘,那干脆别用picutreBox,直接在panel里重绘
你从视频抠的图是什么格式的,位图吗,用libjpeg或libpng压缩后再用空间展示出来试试
已解决,经过公司大佬指点
使用Graphics对背景图片进行缩放,把图片分辨率等比例缩小到1080P以下图片大小缩小到一百多Kb左右
附代码
public string Sized(string imgFile, string SizeImgFile, ImageFormat format)
{
string saveimpfile="";
if (imgFile == "") return saveimpfile;
Bitmap bitmap = new Bitmap(imgFile);
int Width = bitmap.Width;
int Height = bitmap.Height;
while (Width>2000)
{
Width = Width / 2;
Height = Height / 2;
}
Bitmap resizedBmp = new Bitmap(Width, Height);
Graphics graphics = Graphics.FromImage(resizedBmp);
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.DrawImage(bitmap, new Rectangle(0, 0, Width, Height), new Rectangle(0, 0, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel);
saveimpfile = Path.Combine(SizeImgFile, "123.jpeg");
Bitmap copybmp = new Bitmap(resizedBmp);
copybmp.Save(saveimpfile, format);
graphics.Dispose();
resizedBmp.Dispose();
bitmap.Dispose();
copybmp.Dispose();
return saveimpfile;
}