2009-10-16 63 views
0

繼檢索它們後顯示與ASP.NET固定尺寸的圖像是描述連接到MySQL鏈接:如何從MySQL數據庫

http://www.codeproject.com/KB/aspnet/asp_net_and_mysql.aspx

http://www.codeproject.com/KB/aspnet/image_asp.aspx

這裏是代碼從mysql數據庫顯示圖像:

protected void Page_Load(object sender, EventArgs e) 
{  
    MySqlConnection conn = new MySqlConnection(db); 

    conn.Open(); 
    string s; 
    s = Session["t"].ToString(); 

    string commantext = "select img_id,img_file,img_type,img_name from image where img_name='"+s+"'"; 

    // string commantext = "select img_id,img_file,img_type,img_name from image"; 
    // DataSet ds = MySqlHelper.ExecuteDataset(conn, commantext); 

    MySqlCommand cmd = new MySqlCommand(commantext,conn); 
    cmd.Parameters.Add("?img_id", MySqlDbType.Int32).Value = s; 

    // DataTable dt = ds.Tables[0]; 
    DataTable dt = GetData(cmd); 

    while(dt !=null) 
    { 
     Byte[] bytes = (Byte[])dt.Rows[0]["img_file"]; 
     // Byte[] bytes = (Byte[])dt.Rows[1][] ;      
     Response.Buffer = true; 
     Response.Charset = ""; 
     Response.Cache.SetCacheability(HttpCacheability.NoCache); 
     Response.ContentType = dt.Rows[0]["img_type"].ToString(); 
     Response.AddHeader("content-disposition", "attachment;filename=" 
      + dt.Rows[0]["img_name"].ToString()); 

     Response.BinaryWrite(bytes); 
     Response.Flush(); 
     Response.End(); 
    }   
    conn.Close();    
} 


private DataTable GetData(MySqlCommand cmd) 
{ 
    DataTable dt = new DataTable(); 
    //String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString; 

    MySqlConnection con = new MySqlConnection(db); 
    MySqlDataAdapter sda = new MySqlDataAdapter(); 

    cmd.CommandType = CommandType.Text; 
    cmd.Connection = con; 

    try 
    { 
     con.Open(); 
     sda.SelectCommand = cmd; 
     sda.Fill(dt); 
     return dt; 
    } 
    catch 
    { return null; 
    } 
    finally 
    { con.Close(); 
     sda.Dispose(); 
     con.Dispose(); 
    } 
} 

我的代碼上傳圖像文件到mysql數據庫如下。

protected void Button1_Click(object sender,EventArgs e) Stream img_strm = File1.PostedFile.InputStream;

int img_len = File1.PostedFile.ContentLength; 

    string strtype = File1.PostedFile.ContentType; 

    //code snippet to determine image height and width. 
    System.Drawing.Image i = System.Drawing.Image.FromStream(img_strm); 
    int fileheight = int.Parse(i.Width.ToString()); 
    int filewidth = int.Parse(i.Height.ToString()); 



    strname = Text1.Value; 

    //Session["t"] = strname; 

    byte[] imgData = new byte[img_len]; 
    int n = img_strm.Read(imgData, 0, img_len); 
    int result = saveToDb(strname, imgData, strtype); 
} 


private int saveToDb(string imgName, byte[] imgbin, string imgContenttype) 
{ 



    string db = "server=localhost;database=test;uid=root;password=techsoft"; 
    MySqlConnection conn = new MySqlConnection(db); 
    MySqlCommand cmd = new MySqlCommand("insert into image(img_name,img_file,img_type) values(?img_name,?img_file,?img_type)", conn); 

    //MySqlParameter param0 = new MySqlParameter("?img_id", MySqlDbType.Int16, 20); 
    //param0.Value = ; 
    //cmd.Parameters.Add(param0); 

    MySqlParameter param0 = new MySqlParameter("?img_name", MySqlDbType.VarChar, 45); 
    param0.Value = imgName; 
    cmd.Parameters.Add(param0); 

    // MySqlParameter param1 = new MySqlParameter("?img_file", MySqlDbType.VarChar, 45); 
    MySqlParameter param1 = new MySqlParameter("?img_file", MySqlDbType.LongBlob, 10); 
    param1.Value = imgbin; 
    cmd.Parameters.Add(param1); 

    MySqlParameter param2 = new MySqlParameter("?img_type", MySqlDbType.VarChar, 45); 
    param2.Value = imgContenttype; 
    cmd.Parameters.Add(param2); 

    conn.Open(); 

    int num = cmd.ExecuteNonQuery(); 

    conn.Close(); 
    return num; 
} 

我已經使用二進制編寫器來顯示。任何人都可以建議如何以固定尺寸顯示圖像嗎?

+0

不是維基社區發帖。請編輯您的問題 – 2009-10-16 06:40:40

回答

0

感謝所有rip和The_AlienCoder對他們答案的支持。我已經找到了答案,我自己的查詢。

我們需要使用流二進制數據從MySQL數據庫轉換。後面的圖形庫應該用來加載流。同時我們需要根據我們的需要調整圖像大小。


  protected void Page_Load(object sender, EventArgs e){  

      //Create connection to mysql database. 
      MySqlConnection conn = new MySqlConnection(db); 
      conn.Open(); 
      string s; 
      s = Session["t"].ToString(); 

      string commantext = "select img_id,img_file,img_type,img_name from image where img_name='"+s+"'"; 

      MySqlCommand cmd = new MySqlCommand(commantext,conn); 
      cmd.Parameters.Add("?img_id", MySqlDbType.Int32).Value = s; 

      //create datatable. GetData is a method to fetch the data. 
      DataTable dt = GetData(cmd); 

      //Get data from database to bytes. 
      Byte[] bytes = (Byte[])dt.Rows[0]["img_file"]; 

      //Defining the size to display data. 
      int outputSize = 100; 


       if (bytes.Length > 0) 
       { 

        // Open a stream for the image and write the bytes into it 
        System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes, true); 
        stream.Write(bytes, 0, bytes.Length); 
        Bitmap bmp = new Bitmap(stream); 
        Size new_size = new Size(); 

        //resize based on the longer dimension 

        if (bmp.Width > bmp.Height) 
        { 
         new_size.Width = outputSize; 
         new_size.Height = (int)(((double)outputSize/(double)bmp.Width) * (double)bmp.Height); 

        } 
        else 
        { 
         new_size.Width = (int)(((double)outputSize/(double)bmp.Height) * (double)bmp.Width);        
         new_size.Height = outputSize; 

        } 
        Bitmap bitmap = new Bitmap(new_size.Width, new_size.Height, bmp.PixelFormat); 
        Graphics new_g = Graphics.FromImage(bitmap); 
        new_g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; 
        new_g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; 
        new_g.DrawImage(bmp, -1, -1, bitmap.Width + 1, bitmap.Height + 1); 
        bmp.Dispose(); 
        bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); 
        bitmap.Dispose(); 
        new_g.Dispose(); 
        stream.Close(); 
       } 
      } 

private DataTable GetData(MySqlCommand cmd) 
{ 

    DataTable dt = new DataTable(); 
    //String strConnString = System.Configuration.ConfigurationManager .ConnectionStrings["conString"].ConnectionString; 

    MySqlConnection con = new MySqlConnection(db); 
    MySqlDataAdapter sda = new MySqlDataAdapter(); 
    cmd.CommandType = CommandType.Text; 
    cmd.Connection = con; 

    try 
    { 
     con.Open(); 
     sda.SelectCommand = cmd; 
     sda.Fill(dt); 
     return dt; 
    } 

    catch 
    {   return null; 
    } 

    finally 
    { con.Close(); 
     sda.Dispose(); 
     con.Dispose(); 
    } 
} 
} 
0
  1. 我會調整頁面上的圖像大小來顯示它們。他們在哪裏展示?

  • 我將在它們被保存
  • +0

    它們正在直接顯示在頁面上。 我對asp.net非常陌生。您能否告訴我在上傳前如何完成調整大小? U可以參考此鏈接:爲furthur澄清//www.codeproject.com/KB/aspnet/asp_net_and_mysql.aspx :HTTP。它是由我建立 – 2009-10-16 06:56:47

    0

    假設你的唯一的挑戰是隻縮放圖像的時間調整圖像(無論是前上傳或當檢索它們)...這裏是一些代碼,我用它來獲得縮放尺寸的圖像(以適應特定的固定尺寸)......你能堅持在成像類這個地方

    注意,有很多方法...

    public static Size getScaledDimensions(Image img, Int32 maxW, Int32 maxH) 
    { 
    
        //check if image is already within desired dimensions 
        if (img.Height <= maxH & img.Width <= maxW) 
        { 
         Size orgsize = new Size(img.Width, img.Height); 
         return orgsize; // no need to rescale 
        } 
        else //proceed with rescaling 
        { 
    
         int finalH; 
         int finalW; 
    
         //use height/width ratio to determine our new dimensions 
    
         double hwRatio = (double)img.Height/(double)img.Width; 
    
    
          int newW = (int) (maxH/ hwRatio); 
          int newH = (int) (hwRatio * maxW); 
    
          //make sure we scale the right dimension 
          if (newW <= maxW) // scale width 
          { 
           finalH = maxH; 
           finalW = newW; 
          } 
          else 
          { // scale height 
           finalH = newH; 
           finalW = maxW; 
          }//end if 
         Size newsize = new Size(finalW, finalH); 
    
         return newsize; 
    
        } 
    
    +0

    這是很好的代碼,但你能告訴我這到底是怎麼進行的BinaryWriter實施。 – 2009-10-21 06:09:15