调整图像的字节[]大小

本文关键字:大小 字节 图像 调整 | 更新日期: 2023-09-27 17:53:23

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

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

调整图像的字节[]大小

不需要声明byte[],要调整图像大小只需使用

Image image = Image.FromFile(fileName);

检查另一个答案,看看如何缩放图像

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

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

我有一个图片框。我加载一个图像,调整大小并转换成字节,最后发送到sqlite。也许它可以是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;
    }