调整Image的byte []

时间:2013-01-14 09:22:59

标签: c#

从文件对话框中读取后,我想调整图片大小。我完成了以下代码。现在我想调整图片流的大小。我该怎么做?

Stream stream = (Stream)openFileDialog.File.OpenRead();
byte[] bytes = new byte[stream.Length];

3 个答案:

答案 0 :(得分:4)

无需声明byte[],只需使用

调整图像大小
Image image = Image.FromFile(fileName);

检查this other answer以了解如何在此后缩放图像

答案 1 :(得分:2)

试试这个

    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;
    }

用法

        Image img = Image.FromStream(stream);
        Image thumb = ScaleImage(img);
        stream.Close();
        stream.Dispose();
        stream = new MemoryStream();
        thumb.Save(stream, System.Drawing.Imaging.ImageFormat.Png);

答案 2 :(得分:0)

我有一个图片框。我加载一个图像,调整大小并传送到最后发送到sqllite的字节。也许它可能是hlepfıull你的代码在下面。

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;
    }