限制图像大小 [英] Limit image size

查看:42
本文介绍了限制图像大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 WinForm 中有一个 OpenFileDialog,我想何时选择一个图像以将图像的大小限制为 100 Ko,并将尺寸限制为 350x350.

I have an OpenFileDialog in my WinForm and I want when to select an image to limit the image's size in 100 Ko and the Dimensions in 350x350.

我该怎么做??

推荐答案

private bool ValidFile(string filename, long limitInBytes, int limitWidth, int limitHeight)
        {
            var fileSizeInBytes = new FileInfo(filename).Length;
            if(fileSizeInBytes > limitInBytes) return false;

            using(var img = new Bitmap(filename))
            {
                if(img.Width > limitWidth || img.Height > limitHeight) return false;
            }

            return true;
        }

        private void selectImgButton_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if(ValidFile(openFileDialog1.FileName, 102400, 350, 350))
                {
                    // Image is valid and U can
                    // Do something with image
                    // For example set it to a picture box
                    pictureBox1.Image = new Bitmap(openFileDialog1.FileName);
                }
                else
                {
                    MessageBox.Show("Image is invalid");
                }
            }
        }

这篇关于限制图像大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆