Reputation: 2746
I am loading an image from desktop and want to make this image gray-scale. But when I press the button it shows an error.
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;
}
}
}
Showing System.ArgumentException
in this line:
Color newColor = Color.FromArgb(grayScale, grayScale, grayScale);
Upvotes: 1
Views: 882
Reputation: 508
The RGB values in Color.FromArbg(int, int, int)
have to be between 0 and 255 or an ArgumentException is thrown.
Upvotes: 1