前言:经常会遇到需要处理图片大小显示在界面上的情况,这里整理一下两种缩放图片的方法。
1.自己写一个缩放的方法(using System.Drawing)
public Bitmap shrinkTo(Image pic, System.Drawing.Size S, Boolean cutting)
{
Bitmap tmp = new Bitmap(S.Width, S.Height);
Graphics g = Graphics.FromImage(tmp);
g.Clear(Color.FromArgb(0, 0, 0, 0));
Boolean mode = (float)pic.Width / S.Width > (float)pic.Height / S.Height;
if (cutting)
{
mode = !mode;
}
if (mode)
{
S.Height = (int)((float)pic.Height * S.Width / pic.Width);
}
else
{
S.Width = (int)((float)pic.Width * S.Height / pic.Height);
}
System.Drawing.Point P = new System.Drawing.Point((tmp.Width - S.Width) / 2, (tmp.Height - S.Height) / 2);
g.DrawImage(pic, new Rectangle(P, S));
return tmp;
}
2.利用OpenCvSharp实现图片缩放(using OpenCvSharp)
方法实现部分:
public Mat ShrinkTo(Mat mat , OpenCvSharp.Size size)
{
if (mat.Empty())
{
return null;
}
Mat outMat = new Mat();
Cv2.Resize(mat,outMat,size);
return outMat;
}
根据imagebox的Size把加载的图片显示出来
TIP:注意这里用到了OpenCvSharp.Extensions,需要在Nuget中添加拓展并引用。
当然这里可以简化这个语句,或者上面的方法直接输出Bitmap类型,但是由于最近在学习opencvsharp,所以更多去使用和熟悉Mat类
public string SelectPic()
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = false;
dialog.Title = "请选择图片";
dialog.Filter = "图片文件(*.jpg,*.png,*.bmp)|*.jpg;*.png;*.bmp";
if (dialog.ShowDialog() == DialogResult.OK)
{
pictureBoxSrc.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(ShrinkTo(new Mat(dialog.FileName,ImreadModes.AnyColor|ImreadModes.AnyDepth),new OpenCvSharp.Size(pictureBoxSrc.Width,pictureBoxSrc.Height)));
return dialog.FileName;
}
return null;
}
总结:可以看到,利用opencvsharp的Resize方法可以更加省时省力地缩放图片,不用去当那个造船的人,当然要提升自己的算法能力就可以去自己写。