C# 使用 varbinary 调整 jpg 图像大小,转换为字节并保存到数据库中

2023-12-11

我正在尝试调整使用 FileUpload 控件上传的 jpg 图像的大小,并将其转换为字节,然后将其保存到数据库(SQL Server 2008)作为(varbinary(MAX))。我所做的和下面显示的代码是我设法将其转换为字节并以 varbinary(MAX) 形式保存到数据库中。我想知道如何在执行所有这些功能之前调整图像大小。帮帮我吧。谢谢!

读取文件

string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);

根据文件扩展名设置内容类型

string contenttype = String.Empty;            
switch (ext)
{
   case ".jpg":
   contenttype = "image/jpg";
   break;
}

使用varbinary转换为byte并保存到数据库中

if (contenttype != String.Empty)
{
            Stream fs = FileUpload1.PostedFile.InputStream;

            BinaryReader br = new BinaryReader(fs);

            Byte[] bytes = br.ReadBytes((Int32)fs.Length);

            //insert the file into database
            string strQuery = "insert into MemberReport(username, typeofcrime, location, crdatetime, citizenreport, image1, image2, image3, image4, image5)" +
               " values ('" + username + "','" + typeofcrime + "','" + location.Trim() + "','" + datetime + "','" + detail.Trim() + "', @Data, @Data2, @Data3, @Data4, @Data5)";
            SqlCommand cmd = new SqlCommand(strQuery);
            cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
            cmd.Parameters.Add("@Data2", SqlDbType.Binary).Value = bytes2;
            cmd.Parameters.Add("@Data3", SqlDbType.Binary).Value = bytes3;
            cmd.Parameters.Add("@Data4", SqlDbType.Binary).Value = bytes4;
            cmd.Parameters.Add("@Data5", SqlDbType.Binary).Value = bytes5;
            InsertUpdateData(cmd);

            lblMessage.ForeColor = System.Drawing.Color.Green;
            lblMessage.Text = "Report Sent!";

        }
        else
        {
            lblMessage.ForeColor = System.Drawing.Color.Red;
            lblMessage.Text = "File format not recognised." +
              " Upload Image formats";
        }

插入更新数据方法

    private Boolean InsertUpdateData(SqlCommand cmd)
    {
        SqlConnection con = new SqlConnection("Data Source=localhost; Initial Catalog=project; Integrated Security=True");
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
            return true;
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
            return false;
        }
        finally
        {
            con.Close();
            con.Dispose();
        }

您需要将上传的文件转换为Image对象,可以简单地通过以下方式完成:

Image uploaded = Image.FromStream(FileUpload1.PostedFile.InputStream);

接下来,计算出您想要的图像有多大。假设您希望最大尺寸为 256 像素,并保持纵横比。一些代码改编自 CodeProject 文章使用 .NET 动态调整图像大小:

int originalWidth = uploaded.Width;
int originalHeight = uploaded.Height;
float percentWidth = (float)256 / (float)originalWidth;
float percentHeight = (float)256 / (float)originalHeight;
float percent = percentHeight < percentWidth ? percentHeight : percentWidth;
int newWidth = (int)(originalWidth * percent);
int newHeight = (int)(originalHeight * percent);

现在创建一个新的Bitmap对象来包含调整大小的图像(来自同一篇 CodeProject 文章)并将原始图像绘制到其中:

Image newImage = new Bitmap(newWidth, newHeight);
using (Graphics g = Graphics.FromImage(newImage))
{
    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
    g.DrawImage(uploaded, 0, 0, newWidth, newHeight);
}

最后,转换回字节以保存到数据库中:

byte[] results;
using (MemoryStream ms = new MemoryStream())
{
    ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
    EncoderParameters jpegParms = new EncoderParameters(1);
    jpegParms.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
    newImage.Save(ms, codec, jpegParms);
    results = ms.ToArray();
}

我走了很长的路来设置输出的质量水平。如果您不介意使用什么压缩级别,一个简单的img.Save(ms, ImageFormat.Jpeg);call 替换了里面的前 4 行using代码块。

查看代码项目文章我在上面提到了有关调整图像大小的更多信息,并阅读C# 图像到字节数组和字节数组到图像转换器类(也在 CodeProject 上)了解有关将图像与字节数组相互转换的更多信息。


最后一部分,将图像插入数据库表中。我将假设使用 Microsoft SQL,并执行非常简单的表插入。

表定义为:

CREATE TABLE [Images](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [ImageData] [varbinary](max) NULL,
    CONSTRAINT [PK_Images] PRIMARY KEY CLUSTERED 
    (
        [ID] ASC
    ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

以及将图像数据插入表中的代码:

static string connString = "Data Source=localhost; Initial Catalog=project; Integrated Security=True";

public static int InsertImage(byte[] imgdata)
{
    using (SqlConnection conn = new SqlConnection(connString))
    {
        conn.Open();

        using (SqlCommand cmd = new SqlCommand("INSERT INTO Images(ImageData) OUTPUT inserted.ID VALUES(@p1)", conn))
        {
            cmd.Parameters.AddWithValue("@p1", imgdata);

            int res = (int)cmd.ExecuteScalar()
            return res;
        }
    }
}

返回值是SQL为该记录生成的自增值。

或者更新现有图像:

public static void UpdateImage(int id, byte[] imgdata)
{
    using (SqlConnection conn = new SqlConnection(connString))
    {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand("UPDATE Images SET ImageData = @p1 WHERE ID = @p2", conn))
        {
            cmd.Parameters.AddWithValue("@p1", imgdata);
            cmd.Parameters.AddWithValue("@p2", id);

            cmd.ExecuteNonQuery();
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# 使用 varbinary 调整 jpg 图像大小,转换为字节并保存到数据库中 的相关文章

随机推荐