Click here to Skip to main content
15,900,973 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I tried to resize an image using c# by hard coding two values for its width and height but I couldn't figure out a way to resize it on upload without losing its quality.

What I have tried:

This is my code.

{
    OpenFileDialog opendialog;
    SaveFileDialog savedialog;
    Image target_image;
    int width;
    int height;

    public Form1()
    {
        InitializeComponent();
        opendialog = new OpenFileDialog();

        opendialog.RestoreDirectory = true;
        opendialog.InitialDirectory = "C:\\";
        opendialog.FilterIndex = 1;
        opendialog.Filter = "jpg Files (*.jpg)|*.jpg|gif Files (*.gif)|*.gif|png Files (*.png)|*.png |bmp Files (*.bmp)|*.bmp";

        savedialog = new SaveFileDialog();

        savedialog.RestoreDirectory = true;
        savedialog.InitialDirectory = "C:\\";
        savedialog.FilterIndex = 1;
        savedialog.Filter = "jpg Files (*.jpg)|*.jpg|gif Files (*.gif)|*.gif|png Files (*.png)|*.png |bmp Files (*.bmp)|*.bmp";
    }

    private void btnOpen_Click(object sender, EventArgs e)
    {
        try
        {
            if (opendialog.ShowDialog() == DialogResult.OK)
            {
                target_image = Image.FromFile(opendialog.FileName);
                width = target_image.Width;
                height = target_image.Height;
                }


            target_image = Resize(width, height);


        }
        catch (Exception ex)
        {
            MessageBox.Show("Error Occured, " + ex.Message);
        }
    }

    private new Bitmap Resize(int target_width, int target_height)
    {
        target_width = 300;
        target_height = 500;

        Rectangle rectangle = new Rectangle(0, 0, target_width, target_height);
        Bitmap destImage = new Bitmap(target_width, target_height);
        destImage.SetResolution(target_image.HorizontalResolution, target_image.VerticalResolution);
        using (var g = Graphics.FromImage(destImage))
        {
            g.CompositingMode = CompositingMode.SourceCopy;
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;

            using (var wrapmode = new ImageAttributes())
            {
                wrapmode.SetWrapMode(WrapMode.TileFlipXY);
                g.DrawImage(target_image, rectangle, 0, 0, target_image.Width, target_image.Height, GraphicsUnit.Pixel);
            }
        }
        return destImage;
    }

    private void btnSave_Click(object sender, EventArgs e)
    {
        if (savedialog.ShowDialog() == DialogResult.OK)
        {
            target_image.Save(savedialog.FileName);
        }
    }
}
Posted
Updated 26-Aug-18 5:55am

The problem is that when you resize an image, you either had to add information when you make it bigger, or throw it away when you make it smaller.

And that is really difficult, because you don't have the information to add, and you can't get back the information you throw away. Contrary to what you see in movies and TV, images can't be zoomed until you have the detail you want: each pixel is a unit which can't be zoomed any further without adding information.

So when you redraw your image to a specific height and width, you are either throwing away data if the image was bigger, interpolating* what it might be from the surrounding pixels if the image started smaller, or distorting the whole image if the ration y0/y1 : x0/x1 is not the same.

So add insult to injury, every time to save a jpg, you automatically make the quality worse, because jpg is a lossy compression format, which throws away data each time you save. Take a top quality BMP file and save it as a JPG. Open the JPG and save it as a new JPG. Repeat a few times, and you will see really noticeable degradation when you compare against the original.

There isn't anything you can really do about this, unless you know exactly what you are processing as images to start with. (That's why not everybody with a copy of Photoshop can produce good results!)


* I.e. "guessing"
 
Share this answer
 
Comments
Member 13958707 27-Aug-18 2:21am    
Any method to resizing it while preserving the aspect ratio?
OriginalGriff 27-Aug-18 3:52am    
Yes - you either draw it into a bitmap with the same aspect ratio, or you draw it at the same aspect ratio into a bigger bitmap and accept "bars" at the sides or top and bottom.

That's not too complex, all it means is working out the correct size of the new image / drawing by using the x/y ratio of the original.
 
Share this answer
 

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