Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
i want to resize an image with a fix width and heigh after downloading using winforms and c# code.
Any solution please??
Posted

1 solution

This means "resampling". You need to interpolate the image to different size, which means creating a different image.

Here is how: you create a target bitmap of required pixel format and size in pixels:
https://msdn.microsoft.com/en-us/library/3z132tat%28v=vs.110%29.aspx[^].

Then, you create an instance of System.Drawing.Graphics which can be uses to draw on this bitmap: https://msdn.microsoft.com/en-us/library/system.drawing.graphics.fromimage%28v=vs.110%29.aspx[^].

When you draw with this bitmap, you draw on the image instance which was used as a parameter of the call to the factory function referenced above. Now, an important moment comes: as you are going to compose a new image through interpolation, you need to setup options of the Graphics instance to provide appropriate quality. I would advise to chose the best quality in almost all cases. Please see:
https://msdn.microsoft.com/en-us/library/system.drawing.graphics.interpolationmode%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/system.drawing.drawing2d.interpolationmode(v=vs.110).aspx[^],
see also: https://msdn.microsoft.com/en-us/library/system.drawing.graphics.compositingquality%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/system.drawing.graphics.compositingmode(v=vs.110).aspx[^],
https://msdn.microsoft.com/en-us/library/system.drawing.drawing2d.compositingquality(v=vs.110).aspx[^].

When this is done, draw source image on the target bitmap: https://msdn.microsoft.com/en-us/library/system.drawing.graphics.drawimage%28v=vs.110%29.aspx[^].

Use one of the methods which allows you to specify the target size, make it the same as the size of target image, if you want to fill it in. The resulting image will be stretched/collapsed to the required size through interpolation. In most cases, make sure the aspect ratio is the same.
You should remember that resampling bitmaps can only be good if you reduce the size, in worst case, enlarge, but only slightly. Any considerable enlargement will give bad quality, pixellation.

See also my past answers:
resize image in vb.net[^],
Read Big Tiff and JPEG files (>(23000 x 23000) pix) in a stream. And display part of it to the screen in realtime.[^].

—SA
 
Share this answer
 
v2

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