Question Try to resize an image

ilikeyourmom

New member
Joined
Sep 8, 2021
Messages
1
Programming Experience
Beginner
I have been looking all over and cannot find a way to resize and save an image from a picturebox
the open file code is this

C#:
       private void open1_Click(object sender, EventArgs e)
        {
            openImage = new OpenFileDialog();
            openImage.InitialDirectory = "C:\\";
            openImage.Filter = "Image Files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png; *.gif; *.bmp";
            openImage.FilterIndex = 2;
            openImage.RestoreDirectory = true;
            
            if (openImage.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    preview.Image = Image.FromFile(openImage.FileName);
                    imageFile = openImage.FileName;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

and the save file code is

C#:
        private void save1_Click(object sender, EventArgs e)
        {
            string firstText = topText.Text;
            string secondText = bottomText.Text;
            if (preview.Image == null)
            {
                MessageBox.Show("Please Load an image before saving!", "Error!");
                return;
            }
            Bitmap bitmap = (Bitmap)Image.FromFile(imageFile);
            RectangleF TopSize = new RectangleF(0, 10, bitmap.Width, 400);
            RectangleF BottomSize = new RectangleF(0, bitmap.Height -100, bitmap.Width, 400);
            SaveFileDialog saveImage = new SaveFileDialog();
            saveImage.FileName = "*";
            saveImage.DefaultExt = "bmp";
            saveImage.ValidateNames = true;
            saveImage.Filter = "Bitmap Image (.bmp)|*.bmp |Gif Image (.gif)|*.gif |Jpg Image (.jpg)|*.jpg |Png Image (.png)|*.png";
            if (saveImage.ShowDialog() == DialogResult.OK)
            {
                using (Graphics graphics = Graphics.FromImage(bitmap))
                {
                    using (Font memeFont = new Font("Impact", 24, FontStyle.Bold, GraphicsUnit.Point))
                    {
                        graphics.DrawString(firstText, memeFont, Brushes.White, TopSize);
                        graphics.DrawString(secondText, memeFont, Brushes.White, BottomSize);
                    }
                    bitmap.Save(saveImage.FileName);
                }
            }
        }
 
You don't resize an Image object. You create a new Bitmap object with the desired dimensions, create a Graphics object from it and use that to draw the other Image onto it. You then use that new Image in place of the old.
 
Back
Top Bottom