C# .NET - Save Image in database with fix size

Asked By Sohaib Jamil on 04-May-12 01:58 PM
How i upload image on windows form and save in sql database but image size is always fix (130,150 pixels ). it is all done by a user ... he select the image from computer.
kalpana aparnathi replied to Sohaib Jamil on 04-May-12 02:10 PM
hi,

Try below code :

protected void Page_Load(object sender, EventArgs e)
{    
        MySqlConnection con = new MySqlConnection(db);
        con.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,con);
        cmd.Parameters.Add("?img_id", MySqlDbType.Int32).Value = s;

       
       DataTable dt = GetData(cmd);

       
       Byte[] bytes = (Byte[])dt.Rows[0]["img_file"];
      
       int outputSize = 100;

       if (bytes.Length > 0)
       {

            
            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();


            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();
    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();
    }
}
}

Regards,
Venkat K replied to Sohaib Jamil on 04-May-12 11:21 PM
The simple answer is:

You can't fix the image size at sql server. You can only fix the image size when you are binding the image to an picture control.
Just make the picture/image control as fixed in length with 130 and 150 and when you bind the image the picture will be streched (if small) or compressed (if big) and adjust with the above width and height.

NOTE: It is better if you put a text under the upload saying that "Please upload the images of size 130 X 150 to view the images in better resolution.

Thanks
dipa ahuja replied to Sohaib Jamil on 05-May-12 03:40 AM
public bool SaveImage(HttpPostedFile image, string title)
{
  bool result = false;
  int MaxWidth = 500;
  int MaxHeight = 500;
  int ThumbMaxWidth = 150;
  int ThumbMaxHeight = 150;
 
  // Ensure a unique filename
  string upFileName = new Guid().ToString() + image.FileName.Substring(image.FileName.LastIndexOf("."));
 
  // Should put this into a config file.
  string LargeFile = @"UserImages\Large\" + upFileName;
  string ThumbFile = @"UserImages\Thumbs\" + upFileName;
 
  try
  {
    System.Drawing.Image UploadedImage = System.Drawing.Image.FromStream(image.InputStream);
    System.Drawing.Image LargeImage = ImageTool.ToMaxSize(UploadedImage, MaxWidth, MaxHeight);
    System.Drawing.Image ThumbImage = ImageTool.ToMaxSize(UploadedImage, ThumbMaxWidth, ThumbMaxHeight);
 
    LargeImage.Save(Request.PhysicalApplicationPath + LargeFile);
    ThumbImage.Save(Request.PhysicalApplicationPath + ThumbFile);
  }
  catch (Exception ex)
  {
    return false;
  }
 
  GalleryDataContext db = new GalleryDataContext();
 
  // Save the image paths and title to the database using LINQ
  GalleryImage i = new GalleryImage();
  i.FullSize = LargeFile.Replace('\\', '/');
  i.Thumbnail = ThumbFile.Replace('\\', '/');
 
  i.Title = title;
 
  try
  {
    db.GalleryImages.InsertOnSubmit(i);
    db.SubmitChanges();
  }
  catch (Exception ex)
  {
    return false;
  }
 
  return result;
}
<http://www.robbihun.com/Post/ASPNET-Uploading-and-Resizing-Images>
 
 
Sohaib Jamil replied to Venkat K on 06-May-12 07:48 AM
 i develop a database system and use user image who login in this system..... when user sign up and upload differnt size of images. . and i use picture box for it ..... when user upload image of any size it not apper in picture box Full..... 
after upload image by user it auto resize according to size of picture box and save into login table.....
Venkat K replied to Sohaib Jamil on 08-May-12 11:01 AM
If you are expecting the same image size to be saved into database. Either you need to use a third party control to crop the image before uploading.
https://www.google.co.in/#hl=en&sclient=psy-ab&q=image+cropping+in+.net&oq=image+cropping+in+.net&aq=f&aqi=g1g-bK3&aql=&gs_l=hp.3..0j0i8i30l3.1210557.1214558.2.1215064.26.20.2.1.1.0.260.3106.0j18j2.20.0...0.0.3WncvUsUjOc&pbx=1&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.,cf.osb&fp=1143ccadf9dab177&biw=1229&bih=677