3

After reading from file dialog I want to resize a picture. I have the done the following code. Now I want to resize the stream of picture. How do I do it?

Stream stream = (Stream)openFileDialog.File.OpenRead();
byte[] bytes = new byte[stream.Length];
Parimal Raj
  • 20,189
  • 9
  • 73
  • 110
decoder
  • 886
  • 22
  • 46

3 Answers3

4

There is no need to declare a byte[], to resize an image just use

Image image = Image.FromFile(fileName);

check this other answer to see how to scale the image aftewards

Community
  • 1
  • 1
istepaniuk
  • 4,016
  • 2
  • 32
  • 60
2

try this

    public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
    {
        var ratioX = (double)maxWidth / image.Width;
        var ratioY = (double)maxHeight / image.Height;
        var ratio = Math.Min(ratioX, ratioY);

        var newWidth = (int)(image.Width * ratio);
        var newHeight = (int)(image.Height * ratio);

        var newImage = new Bitmap(newWidth, newHeight);
        Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
        return newImage;
    }

Usage

        Image img = Image.FromStream(stream);
        Image thumb = ScaleImage(img);
        stream.Close();
        stream.Dispose();
        stream = new MemoryStream();
        thumb.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
Parimal Raj
  • 20,189
  • 9
  • 73
  • 110
1

I have an picturebox. I load an image, resizing and conveting to byte at last sending to sqllite. Maybe it can be hlepfıull to you Code is below.

private static byte[] byteResim = null;

    private void btnResimEkle_Click(object sender, EventArgs e)
    {
        openFileDialog1.Title = "Resimdosyası seçiniz.";
        openFileDialog1.Filter = "Resim files (*.jpg)|*.jpg|Tüm dosyalar(*.*)|*.*";
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {

            string resimYol = openFileDialog1.FileName; // File name of the image

            picResim.Image = Image.FromFile(resimYol);// picResim is name of picturebox
            picResim.Image = YenidenBoyutlandir(new Bitmap(picResim.Image)); //this method resizing the image
            Image UyeResim = picResim.Image;   // and this four block converting to image to byte
            MemoryStream ms = new MemoryStream();
            UyeResim.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byteResim = ms.ToArray();  // byteResim  variable format  Byte[]

        }
    }



    Image YenidenBoyutlandir(Image resim)// resizing image method 

    {
        Image yeniResim = new Bitmap(150, 156);
        using (Graphics abc = Graphics.FromImage((Bitmap)yeniResim))
        {
            abc.DrawImage(resim, new System.Drawing.Rectangle(0, 0, 150, 156));
        }
        return yeniResim;
    }