仅作为记录,大佬请跳过。
参考:感谢大佬博主文章传送门
先前准备:建立c#的winform界面——界面里仅拖入一个button
和一个panel1
,分别命名为button1和panel1
博主实现的源代码
根据大佬博主文章中修改了一个bug后,可运行的程序:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Imaging;
namespace a1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Image s = Image.FromFile("E:\\brest_grade\\HEimg_tmp\\5_159002_86092.png");
Image bgImage = ZoomPicture(s, 0.5f, 0.5f); //M,N大于1,为放大图片,小于1为缩小图片
panel1.Width = bgImage.Width; //设置画板宽度为图片宽度
panel1.Height = bgImage.Height; //设置画板高度为图片高度
panel1.BackgroundImage = bgImage;
Bitmap bmap = new Bitmap(bgImage);
bmap.Save("E:\\brest_grade\\HEimg_tmp\\5.png", ImageFormat.Png);
bmap.Dispose();
}
// 按比例缩放图片
public Image ZoomPicture(Image SourceImage, float M, float N)
{
int IntWidth; //新的图片宽
int IntHeight; //新的图片高
int TargetWidth = (int)(M * SourceImage.Width); //取整,是因为下面的Bitmap的两个参数只能为整数
int TargetHeight = (int)(N * SourceImage.Height);
try
{
ImageFormat format = SourceImage.RawFormat;
Bitmap SaveImage = new Bitmap(TargetWidth, TargetHeight);
Graphics g = Graphics.FromImage(SaveImage);
g.Clear(Color.White);
//计算缩放图片的大小
IntHeight = TargetHeight;
IntWidth = TargetWidth;
g.DrawImage(SourceImage, 0, 0, IntWidth, IntHeight); //在指定坐标处画指定大小的图片
SourceImage.Dispose();
return SaveImage;
}
catch (Exception ex)
{
}
return null;
}
}
}
展示