c#实现图片缩放【实测成功】

仅作为记录,大佬请跳过。

参考:感谢大佬博主文章传送门


先前准备:建立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;
        }


    }
}

展示

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值