2009-12-19 307 views
0

嗨,非常感謝我在這段代碼下面有一個代碼,上傳一張圖片。將其轉換爲 字節代碼,並將其存儲在數據庫..並在GridView中檢索..在 將它轉換爲字節碼之前我想調整它的大小它可以告訴我什麼代碼,我應該在這裏插入...謝謝很多......調整圖像大小。 。 。 。

protected void btnUpload_Click(object sender, EventArgs e) 
{ 
string strID= txtid.Text.ToString(); 
string strImageName = txtName.Text.ToString(); 
if (FileUpload1.PostedFile != null && 
    FileUpload1.PostedFile.FileName != "") 
    { 


    byte[] imageSize = new byte 
       [FileUpload1.PostedFile.ContentLength]; 

    HttpPostedFile uploadedImage = FileUpload1.PostedFile; 
    uploadedImage.InputStream.Read 
    (imageSize, 0, (int)FileUpload1.PostedFile.ContentLength); 

// Create SQL Connection 
    SqlConnection con = new SqlConnection("user id=sa;[email protected];database=salary_db;server=192.168.1.100"); 


// Create SQL Command 

SqlCommand cmd = new SqlCommand(); 
cmd.CommandText = "INSERT INTO image1(ID,ImageName,Image)" + 
        " VALUES (@ID,@ImageName,@Image)"; 
cmd.CommandType = CommandType.Text; 
cmd.Connection = con; 


SqlParameter ID = new SqlParameter 
        ("@ID", SqlDbType.VarChar, 50); 
ID.Value = strID.ToString(); 
cmd.Parameters.Add(ID); 

SqlParameter ImageName = new SqlParameter 
        ("@ImageName", SqlDbType.VarChar, 50); 
ImageName.Value = strImageName.ToString(); 
cmd.Parameters.Add(ImageName); 

SqlParameter UploadedImage = new SqlParameter 
       ("@Image", SqlDbType.Image, imageSize.Length); 
UploadedImage.Value = imageSize; 
cmd.Parameters.Add(UploadedImage); 
con.Open(); 
int result = cmd.ExecuteNonQuery(); 
con.Close(); 
if (result > 0) 
lblMessage.Text = "File Uploaded"; 

GridView1.DataBind(); 

}} 
+6

與問題無關,但仍然很重要:不要使用SA帳戶連接到您的數據庫,也不要在您的代碼中內聯SQL代碼。在web.config中使用適當的connectionStrings部分。 –

+1

與問題有點相關:考慮將圖像存儲爲文件並將文件路徑存儲在數據庫中。存儲它們不僅會擴大數據庫的大小,還會影響性能,特別是在圖像很大的情況下。 –

回答

3

您可以使用下面的功能:

public void ResizeImage(double scaleFactor, Stream fromStream, Stream toStream) 
{ 
    using (var image = Image.FromStream(fromStream)) 
    { 
     var newWidth = (int)(image.Width * scaleFactor); 
     var newHeight = (int)(image.Height * scaleFactor); 
     using (var thumbnailBitmap = new Bitmap(newWidth, newHeight)) 
     using (var thumbnailGraph = Graphics.FromImage(thumbnailBitmap)) 
     { 
      thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality; 
      thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality; 
      thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic; 
      var imageRectangle = new Rectangle(0, 0, newWidth, newHeight); 
      thumbnailGraph.DrawImage(image, imageRectangle); 
      thumbnailBitmap.Save(toStream, image.RawFormat); 
     } 
    } 
} 

參數的名稱應該是不言自明的。