winfrom-OpenFileDialog选择图片并设定大小

本文介绍了如何在Windows Forms应用程序中利用OpenFileDialog组件让用户选择图片,并通过编程方式来调整所选图片的大小。详细步骤包括打开文件对话框、读取图像文件以及设置新的尺寸。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class selectimg : Form
    {
        public selectimg()
        {
            InitializeComponent();
            this.pictureBox1.BorderStyle = BorderStyle.FixedSingle;
            this.openFileDialog1.Filter = "图片|*.jpg;*.png";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                Image fromImage = Image.FromFile(this.openFileDialog1.FileName);
                fromImage = fromImage.AdjImageToFitSize(pictureBox1.Width, pictureBox1.Height); //350
                this.pictureBox1.Image = fromImage;
            }
        }

        //...

    }

    internal static class ImgHelp
    {
        /// <summary>
        /// 获取等比例缩放的图片(高宽不一致时获取最中间部分的图片)
        /// </summary>
        public static Image AdjImageToFitSize(this Image fromImage, int width, int height)
        {
            Bitmap bitmap = new Bitmap(width, height);

            Graphics graphics = Graphics.FromImage(bitmap);
            Point[] destPoints = new Point[] {
                new Point(0, 0),
                new Point(width, 0),
                new Point(0, height)
            };

            Rectangle rect = GetImageRectangle(fromImage.Width, fromImage.Height);
            graphics.DrawImage(fromImage, destPoints, rect, GraphicsUnit.Pixel);

            Image image = Image.FromHbitmap(bitmap.GetHbitmap());
            bitmap.Dispose();
            graphics.Dispose();
            return image;
        }
        /// <summary>
        /// 居中位置获取
        /// </summary>
        private static Rectangle GetImageRectangle(int w, int h)
        {
            int x = 0;
            int y = 0;

            if (h > w)
            {
                h = w;
                y = (h - w) / 2;
            }
            else
            {
                w = h;
                x = (w - h) / 2;
            }

            return new Rectangle(x, y, w, h);
        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值