Click here to Skip to main content
Click here to Skip to main content
Articles » Database » Database » General » Downloads
 
Add your own
alternative version

Tagged as

Display/Store and Retrieve Image Data from Database to Gridview, and also on Mouse Over

, 15 Oct 2011 CPOL
How to Display/Store and Retrieve Image Data from Database to Gridview, and also on mouse over
UserSample.zip
UserSample
~$gemArticle.docx
AlgemArticle.docx
Sample
App_Code
App_Data
Bin
AjaxControlToolkit.dll
AjaxControlToolkit.dll.refresh
Utils.dll
Utils.dll.refresh
Utils.pdb
css
Images
accordionHeaderIcon.png
BlackLoadingBar.gif
btn_delete.gif
btn_edit.gif
Calendar.png
close.gif
Copy of gridheader.gif
del.png
downarrow.gif
excel_icon.gif
gridfooter.gif
gridfooter.JPG
gridheader.gif
headermenu.jpg
headerpanel.jpg
lock.png
loginbg.jpg
LoginPanelBG.png
minniloader.gif
pdf.jpg
print-button.gif
scan.gif
spicture.gif
spicture.jpg
Thumbs.db
txt.png
view.gif
js
arrowdown.gif
arrowup.gif
Members.JPG
Sample (3).suo
Show
Algem_G_Mojedo.jpg
Asds_A_Asdasd.jpg
Firstname_M_Lastname.jpg
Sdfdfsdf_S_Sdfsdf.jpg
Test_T_Test.jpg
Test1_T_Resr1.jpg
Thumbs.db
Zxdzx_Z_Zxzx.jpg
upload
UsersControl
Utils
Utils
bin
Debug
Utils.dll
Utils.pdb
obj
Debug
Refactor
TempPE
Utils.dll
Utils.pdb
Properties
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Configuration;
using System.Data.SqlClient;
using System.Text;
using System.Net;

/// <summary>
/// Author: Algem Mojedo
/// Date: 9/25/2011
/// </summary>

[Serializable]
internal class Manage
{
    private const string FILEUPLOAD = "FileUpload";
    public static string SessionFileZise
    {
        get
        {
            if (HttpContext.Current.Session[FILEUPLOAD] == null)
            {
                return string.Empty;
            }
            else
            {
                return HttpContext.Current.Session[FILEUPLOAD].ToString();
            }
        }
        set
        {
            HttpContext.Current.Session[FILEUPLOAD] = value;
        }
    }

}

public partial class UsersControl_UserAccountUC : System.Web.UI.UserControl
{
    public void DisplayInfo(object sender, EventArgs e)
    {
        this.Image1 = null;
        Page_Load(sender, e);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (this.Image1 == null)
        {


        }

    }

    protected void ShowMessage(string message, int fileUploadPos)
    {
        if (fileUploadPos == 0)
        {
            Label1.Text = message;
        }
    }

    protected void btnClose_Click(object sender, ImageClickEventArgs e)
    {

        Page.GetType().InvokeMember("CloseModalUserAccountUC", System.Reflection.BindingFlags.InvokeMethod, null, Page, null);
        this.Dispose();
    }
    protected void btnClear_Click(object sender, EventArgs e)
    {
        this.Image1 = null;
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (this.txtPassword.Text != this.txtPasswordConf.Text)
        {
            this.Label1.Text = "Password confirmation not equal!";
            Page.GetType().InvokeMember("IvokeAdd", System.Reflection.BindingFlags.InvokeMethod, null, Page, null);
            return;
        }
        if (this.txtFirstName.Text == string.Empty)
        {
            this.Label1.Text = "First Name text box should not empty!";
            Page.GetType().InvokeMember("IvokeAdd", System.Reflection.BindingFlags.InvokeMethod, null, Page, null);
            return;
        }
        if (this.txtMiddleName.Text == string.Empty)
        {
            this.Label1.Text = "Middle Name text box should not empty!";
            Page.GetType().InvokeMember("IvokeAdd", System.Reflection.BindingFlags.InvokeMethod, null, Page, null);
            return;
        }
        if (this.txtLastName.Text == string.Empty)
        {
            this.Label1.Text = "Last Name text box should not empty!";
            Page.GetType().InvokeMember("IvokeAdd", System.Reflection.BindingFlags.InvokeMethod, null, Page, null);
            return;
        }
        if (this.txtPassword.Text.Length < 8)
        {
            this.Label1.Text = "Password length should not lesser that 8!";
            Page.GetType().InvokeMember("IvokeAdd", System.Reflection.BindingFlags.InvokeMethod, null, Page, null);
            return;
        }
        bool success = false;
        HttpFileCollection uploadFilCol = null;
        FileUpload img = null;
        FileUpload imgUpload = null;
        var originalSize = Tools.Tools.IifInt(Manage.SessionFileZise);
        try
        {
            HttpFileCollection uploadFil = Request.Files;
            uploadFilCol = uploadFil;
            imgUpload = (FileUpload)Session["UploadFile2"];
            img = (FileUpload)imgUpload;
            originalSize = Tools.Tools.IifInt(Manage.SessionFileZise);
        }
        catch (Exception)
        {
            return;
        }
        var targetDir = Server.MapPath("./upload/");
        var sourceDirFile = Server.MapPath("./images/");
        string[] files = Directory.GetFiles(targetDir);
        if (this.Image1.ImageUrl == string.Empty)
        {
            // Save record with default image NoImage...
            int id = SaveRecord(false, imgUpload, img, originalSize,
                sourceDirFile, files);
        }
        else
        {
            int id = SaveRecord(true, imgUpload, img, originalSize,
               sourceDirFile, files);
        }

        try
        {
            foreach (string file in files)
            {
                File.SetAttributes(file, FileAttributes.Normal);
                File.Delete(file);
            }
        }
        catch (FileNotFoundException)
        {

        }
        this.FileUpload1.Dispose();
        success = true;
        this.Label1.Text = "Record was successfuly save.";

        if (success)
        {
            Page.GetType().InvokeMember("CloseModalUserAccountUC", System.Reflection.BindingFlags.InvokeMethod, null, Page, null);
        }
    }


    private int SaveRecord(bool withImage, FileUpload imgUpload, FileUpload img,
        int originalSize, string sourceDirFile, string[] files)
    {
        SqlConnection connection = null;
        User user = new User();
        Byte[] imgByte = null;
        try
        {
            if (img.HasFile && img.PostedFile != null)
            {
                //To create a PostedFile
                HttpPostedFile File = imgUpload.PostedFile;
                //Create byte Array with file len
                imgByte = new Byte[File.ContentLength];
                //force the control to load data in array
                File.InputStream.Read(imgByte, 0, File.ContentLength);
                originalSize = File.ContentLength;
            }
        }
        catch
        {

        }
        try
        {
            user.Username = this.txtUserName.Text;
            user.Password = this.txtPassword.Text;
            user.LastName = this.txtLastName.Text.Substring(0, 1).ToUpper() +
                            this.txtLastName.Text.Substring(1).ToLower();
            user.FirstName = this.txtFirstName.Text.Substring(0, 1).ToUpper() +
                             this.txtFirstName.Text.Substring(1).ToLower();
            user.MiddleName = this.txtMiddleName.Text.ToUpper().Substring(0, 1) +
                              this.txtMiddleName.Text.Substring(1).ToLower();
            user.WorksiteCode = "1";
            user.AccessLevel = Tools.Tools.IifInt(this.ddlAccessLevel.SelectedValue.ToString());
            if (this.chkActive.Checked)
            {
                user.Active = "Y";
            }
            else
            {
                user.Active = "N";
            }
            user.DateCreated = DateTime.Now;
            //user.DateUpdated = DateTime.Now;
            user.Worksitedesc = "1";
            //===============================
            string userName = CleanText(user.Username);
            string password = CleanText(user.Password);
            string lastName = CleanText(user.LastName);
            string firstName = CleanText(user.FirstName);
            string middleName = CleanText(user.MiddleName);
            string workSiteCode = CleanText(user.WorksiteCode);
            int accessLevel = user.AccessLevel;
            string active = CleanText(user.Active);
            DateTime dateCreated = user.DateCreated;
            string workSiteDesc = CleanText(user.Worksitedesc);
            // ==========
            Size eimgFullSize = new Size();
            eimgFullSize.Height = 400;
            eimgFullSize.Width = 400;
            //---
            Size eimgThumbSize = new Size();
            eimgThumbSize.Height = 100;
            eimgThumbSize.Width = 100;
            //-- 
            Size eimgPosterSize = new Size();
            eimgPosterSize.Height = 250;
            eimgPosterSize.Width = 250;
            // Here we have three dimesion size of image to produce...
            Byte[] eimgFull = null;
            Byte[] eimgThumb = null;
            Byte[] eimgPoster = null;
            //========
            if (withImage)
            {
                eimgFull = ResizeImageFile(imgByte, eimgFullSize);         
                eimgThumb = (Byte[])ResizeImageFile(imgByte, eimgThumbSize); 
                eimgPoster = (Byte[])ResizeImageFile(imgByte, eimgPosterSize);  
            }
            else
            {
                // Read the default NoImage file
                System.Drawing.Image image1 = System.Drawing.Image.FromFile(sourceDirFile + "\\spicture.jpg");
                imgByte = ImageToByte2(image1);
                eimgFull = ResizeImageFile(imgByte, eimgFullSize);            
                eimgThumb = (Byte[])ResizeImageFile(imgByte, eimgThumbSize);  
                eimgPoster = (Byte[])ResizeImageFile(imgByte, eimgPosterSize);  

            }
            // Insert the employee name and image into db
            string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            connection = new SqlConnection(conn);
            connection.Open();
            StringBuilder sb = new StringBuilder();
            sb.Append("INSERT INTO dbo.[User](");
            sb.Append("Username,Password,LastName,FirstName,MiddleName,WorksiteCode,");
            sb.Append("AccessLevel,Active,DateCreated,Worksitedesc,Picture,ImageFull ");
            sb.Append(") VALUES (");
            sb.Append("@userName ,@password,@lastName,@firstName,");
            sb.Append("@middleName,@worksiteCode,@accessLevel,@active,");
            sb.Append("@dateCreated,@worksitedesc,");
            sb.Append("@eimgThumb,@eimgFull) ");  // For Picture image
            sb.Append(" SELECT @@IDENTITY");
            string sql = sb.ToString();
            //----------
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.Parameters.AddWithValue("@userName", user.Username);
            cmd.Parameters.AddWithValue("@password", user.Password);
            cmd.Parameters.AddWithValue("@lastName", user.LastName);
            cmd.Parameters.AddWithValue("@firstName", user.FirstName);
            cmd.Parameters.AddWithValue("@middleName", user.MiddleName);
            cmd.Parameters.AddWithValue("@worksiteCode", user.WorksiteCode);
            cmd.Parameters.AddWithValue("@accessLevel", user.AccessLevel);
            cmd.Parameters.AddWithValue("@active", user.Active);
            cmd.Parameters.AddWithValue("@dateCreated", user.DateCreated);
            cmd.Parameters.AddWithValue("@worksitedesc", user.Worksitedesc);
            cmd.Parameters.AddWithValue("@eimgThumb", eimgThumb);
            cmd.Parameters.AddWithValue("@eimgFull", eimgFull);
            int id = Convert.ToInt32(cmd.ExecuteScalar());
            connection.Close();
         
            Size targetSize = new Size();
            targetSize.Width = 100;
            targetSize.Height = 100;

            //========= 
            // Save File to Show sub directory 
            // Must be in fix length 
            string targetPath = Server.MapPath("./Show/");
            string fleName = (firstName.Trim() + "_" + middleName.Substring(0, 1) + "_" + lastName).Trim() + ".jpg";
            File.WriteAllBytes(@targetPath + @fleName, eimgPoster);
            return id;
        }
        catch
        {
            return 0;
        }
    }
    private string CleanText(string p)
    {
        string str = string.Empty;
        if (p != string.Empty)
        {
            str = p.Replace("&nbsp;", "");
        }
        return str;
    }

    public static byte[] ImageToByte2(System.Drawing.Image img)
    {
        byte[] byteArray = new byte[0];
        using (MemoryStream stream = new MemoryStream())
        {
            img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
            stream.Close();
            byteArray = stream.ToArray();
        }
        return byteArray;
    }

    private byte[] ResizeImageFile(byte[] imageFile, Size targetSize)
    {
        using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile)))
        {
            Size newSize = CalculateDimensions(oldImage.Size, targetSize.Height, targetSize.Width);
            using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb))
            {
                using (Graphics canvas = Graphics.FromImage(newImage))
                {
                    canvas.SmoothingMode = SmoothingMode.AntiAlias;
                    canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
                    MemoryStream m = new MemoryStream();
                    newImage.Save(m, ImageFormat.Jpeg);
                    return m.GetBuffer();
                }
            }
        }
    }

    private Size CalculateDimensions(Size oldSize, int targetH, int targetW)
    {
        Size newSize = new Size();
        if (oldSize.Height > oldSize.Width)
        {
            newSize.Width = targetW;
            newSize.Height = targetH;
        }
        else
        {
            //Make the image as uniform with fix size.
            newSize.Width = targetW;
            newSize.Height = targetH;
        }
        return newSize;
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        this.btnSave.Enabled = false;
        bool hasFile = false;
        string fileName = string.Empty;
        HttpPostedFile file = null;
        HttpFileCollection uploadFilCol = Request.Files;

        hasFile = true;
        HttpPostedFile file2 = uploadFilCol[0];
        if (file2.ContentLength == 0)
        {
            return;
        }
        file = uploadFilCol[0];
        Session["UploadFile2"] = FileUpload1;
        Manage.SessionFileZise = file.ContentLength.ToString();
        string fileExt = Path.GetExtension(file.FileName).ToLower();
        fileName = Path.GetFileName(file.FileName);
        if (fileName != string.Empty)
        {
            try
            {
                if (fileExt == ".jpg" || fileExt == ".gif")
                {
                    file.SaveAs(Server.MapPath("./upload/") + fileName);
                    this.ShowMessage(" " + fileName + " Successfully Uploaded", 0);

                }
                else
                {
                    // We do allow image file only
                    this.Label1.Text = "Valid files to upload is .jpg and .gif only!";
                    Page.GetType().InvokeMember("IvokeAdd", System.Reflection.BindingFlags.InvokeMethod, null, Page, null);
                    return;
                }
                this.hfUrl.Value = fileName;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        string fileImgName = "~/upload/" + fileName;
        this.Image1.ImageUrl = fileImgName;
        upImg.Update();

        if (hasFile)
        {
            this.btnSave.Enabled = true;
            Page.GetType().InvokeMember("IvokeAdd", System.Reflection.BindingFlags.InvokeMethod, null, Page, null);
        }
        else
        {
            this.btnSave.Enabled = false;
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Al Moje
Software Developer (Senior) ***
Philippines Philippines
MCTS - Microsoft Certified Technology Specialist.
An Accountant.
Had been developed Payroll Accounting System Application
Live in: Quezon City, Metro Manila Philippines
Could reached at email address: ag_mojedo@live.com

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150302.1 | Last Updated 15 Oct 2011
Article Copyright 2011 by Al Moje
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid