I want to convert an image from bitmap to grayscale, but when I load it in a picturebox...not on a button click event...
Like this...I load a bitmap picture and in the picturebox and it appears directly as a grayscale picture...
I found some source code on the Internet, but I don't really kmow how where to put the code to do what I want...
Thank you
Loading
FroglegPosted Jan 17, 2011, 10:40 PM
Bitmap bmp;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// loadImage();//use this to autoload
}
public void loadImage()
{
Image img = Image.FromFile("po.bmp");
bmp = new Bitmap(img.Width, img.Height);
Graphics g = Graphics.FromImage(bmp);
g.DrawImage(img, 0, 0);
pictureBox1.Image = ConvertToGrayscale(bmp);
}
public Bitmap ConvertToGrayscale(Bitmap source)
{
Bitmap bm = new Bitmap(source.Width, source.Height);
for (int y = 0; y < bm.Height; y++)
{
for (int x = 0; x < bm.Width; x++)
{
Color c = source.GetPixel(x, y);
int luma = (int)(c.R * 0.3 + c.G * 0.59 + c.B * 0.11);
bm.SetPixel(x, y, Color.FromArgb(luma, luma, luma));
}
}
return bm;
}
private void button1_Click(object sender, EventArgs e)
{
loadImage();
}
Try this. To load automatically uncomment
// loadImage();//use this to autoload
or put loadImage(); in open file dialog
Kip HackmanPosted Dec 23, 2020, 10:30 PM
luci margineanPosted Jan 18, 2011, 7:10 AM
private void btnLoad_Click(object sender, EventArgs e)
{
OpenFileDialog fDialog = new OpenFileDialog();
fDialog.Filter =
"Bitmaps |*.bmp| GIFs |*.gif| JPEGs |*.jpg;*.jpeg| TIFs |*.tif";
fDialog.InitialDirectory = @"C:\Documents and Settings\Taticu\Desktop\Scoala\Poze proba";
if (fDialog.ShowDialog() == DialogResult.OK)
{
Image old = Image.FromFile(fDialog.FileName);
pcbImage.Image = (Image)Grayscale(new Bitmap(old));
pcbImage.SizeMode = PictureBoxSizeMode.AutoSize;
}
}
public static Bitmap Grayscale(Bitmap original)
{
Bitmap newBitmap = new Bitmap(original.Width, original.Height);
Graphics g = Graphics.FromImage(newBitmap);
ColorMatrix colorMatrix = new ColorMatrix(
new float[][]
{
new float[] {.3f, .3f, .3f, 0, 0},
new float[] {.59f, .59f, .59f, 0, 0},
new float[] {.11f, .11f, .11f, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}
});
ImageAttributes attributes = new ImageAttributes();
attributes.SetColorMatrix(colorMatrix);
g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);
g.Dispose();
return newBitmap;
}