簡體   English   中英

C#調整jpg圖像,轉換為字節並使用varbinary保存到數據庫中

[英]C# Resize jpg image, convert to byte and save into database using varbinary

我正在嘗試調整我使用FileUpload控件上傳的jpg圖像,並在將其保存到數據庫(SQL Server 2008)之前將其轉換為byte(varbinary(MAX))。 我所做的和下面的代碼顯示我設法將其轉換為字節並作為varbinary(MAX)保存到數據庫中。 我想知道如何在完成所有這些功能之前調整圖像大小。 幫幫我吧 謝謝!

閱讀文件

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

根據文件擴展名設置contenttype

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

轉換為字節並使用varbinary保存到數據庫中

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

InsertUpdateData方法

    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取代了using代碼塊中的前4行。

查看我上面提到的CodeProject文章 ,了解有關調整圖像大小的更多信息,並閱讀C#Image to Byte Array和Byte Array To Image Converter Class (也在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();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM