Click here to Skip to main content
15,881,139 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have applied the size mode==StretchImage but still not working
it is showing only 20% image and rest of the picture box in gray color
Posted
Comments
AmitGajjar 10-Apr-13 8:54am    
can you share your code ?

1 solution

Refere this code. basic idea is calculate height and width of your picture box and apply on your image to fit into picture box.

code:-
C#
        int PicBoxHeight = 0;
	int PicBoxWidth = 0;
	int ImageHeight = 0;
	int ImageWidth = 0;
	Image TempImage = default(Image);
	float scale_factor = 0;
	PictureBox1.SizeMode = PictureBoxSizeMode.Normal;
	// Get control size
	PicBoxHeight = PictureBox1.Height;
	PicBoxWidth = PictureBox1.Width;
// Load the image. Change Image.FromFile() to match your code
	TempImage = Image.FromFile("D:\\Download\\Image00b.jpg");
	// Get image size
	ImageHeight = TempImage.Height;
	ImageWidth = TempImage.Width;
	// Calculate scale_factor
	scale_factor = 1.0;
	// No scaling by default i.e. image fits in the Box
	// 1) Height
	if (ImageHeight > PicBoxHeight) {
		// Reduce height first
		scale_factor = Convert.ToSingle(PicBoxHeight / ImageHeight);
	}
	// 2) Width. Notice, we do know now how much we have to scale down the height
	// and the scale_factor affects width too
	if ((ImageWidth * scale_factor) > PicBoxWidth) {
		// Scaled width exceeds Box's width, recalculate scale_factor
		scale_factor = Convert.ToSingle(PicBoxWidth / ImageWidth);
	}
	// Move image to control for resizing
	PictureBox1.Image = TempImage;
	// Get the source bitmap.
	Bitmap bm_source = new Bitmap(PictureBox1.Image);
	// Make a bitmap for the result.
	Bitmap bm_dest = new Bitmap(Convert.ToInt32(bm_source.Width * scale_factor), Convert.ToInt32(bm_source.Height * scale_factor));
	// Make a Graphics object for the result Bitmap.
	Graphics gr_dest = Graphics.FromImage(bm_dest);
	// Copy the source image into the destination bitmap.
	gr_dest.DrawImage(bm_source, 0, 0, bm_dest.Width + 1, bm_dest.Height + 1);
	// Display the result.
	PictureBox1.Image = bm_dest;
 
Share this answer
 
v2
Comments
fjdiewornncalwe 10-Apr-13 10:14am    
Plagiarized from: Source
ALWAYS cite the source when you copy/paste something.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900