System.Drawing.dll中出现灰色等级的“System.ArgumentException”类型的未处理异常

时间:2015-02-10 01:57:13

标签: c#

我正在从桌面加载图像,并希望将此图像设置为灰度。但是当我按下按钮时会显示错误。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Windows.Forms.Layout;

namespace OCRC
{
    public partial class Form1 : Form
    {

        Bitmap newBitmap;
        Image file;
        bool opened = false;


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {

        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            DialogResult dr = openFileDialog.ShowDialog();
            //openFileDialog.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp; *.png; *.PNG";

            if(dr==DialogResult.OK)
            {
                file = Image.FromFile(openFileDialog.FileName);
                newBitmap = new Bitmap(openFileDialog.FileName);
                pictureBox1.Image = file;
                opened = true;
            }
          }

        private void button2_Click(object sender, EventArgs e)
        {

        }

        private void button6_Click(object sender, EventArgs e)
        {
            int x, y;

            for(x=0; x < newBitmap.Width; x++)
            {
                for(y=0; y < newBitmap.Height; y++)
                {
                    Color originalColor = newBitmap.GetPixel(x, y);
                    int grayScale = (int)((originalColor.R * 3) + (originalColor.G * 0.59) + (originalColor.B * 0.11));

                    Color newColor = Color.FromArgb(grayScale, grayScale, grayScale);
                    newBitmap.SetPixel(x, y, newColor); 

                }
            }

            pictureBox1.Image = newBitmap;
        }

        }

}

在此行中显示System.ArgumentException

Color newColor = Color.FromArgb(grayScale, grayScale, grayScale);

1 个答案:

答案 0 :(得分:1)

Color.FromArbg(int, int, int)中的RGB值必须介于0到255之间,否则会抛出ArgumentException。