I had managed to let users upload the image and save into the database and the folder. I need to generate thumbnail from the image and save into the database and the folder as well. But there is some error with generating thumbnail. Can someone help with me with it? Thank you

protected void Button1_Click(object sender, EventArgs e)
        {
            //Get Filename from fileupload control
            string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
            //Save images into Images folder
            FileUpload1.SaveAs(Request.MapPath("/Images/uploaded/" + filename));
            //Getting dbconnection from web.config connectionstring
            SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
            using (SqlDataAdapter adapter = new SqlDataAdapter("select ImageName from Images", connection))
            //Open the database connection
            {
                DataTable dt = new DataTable();
                adapter.Fill(dt);
                DataList1.DataSource = dt;
                DataList1.DataBind();
            }
            connection.Open();
            //Query to insert images path and name into database
            SqlCommand cmd = new SqlCommand("Insert into Images(ImageName) values(@ImageName)", connection);
            //Passing parameters to query
            cmd.Parameters.AddWithValue("@ImageName", filename);
            cmd.ExecuteNonQuery();
            //Close dbconnection
            connection.Close();
            string strImage = FileUpload1.FileName.ToString();
            if(FileUpload1.HasFile)
            {
            strImage = FileUpload1.FileName.ToString();
            //check whether the file exists or not
            if (!File.Exists(Request.MapPath("/Images/uploaded/") + strImage)) //testing
            {
            
           //create a new file name with grid
                strImage = Guid.NewGuid().ToString().Substring(0,8) + strImage.Substring(strImage.IndexOf('.'));
      
            }
            //save the file
            FileUpload1.SaveAs(Request.MapPath("/Images/uploaded/") + strImage); //testing
            // create an image object, using the filename we just retrieved
            System.Drawing.Image image = System.Drawing.Image.FromFile(Request.MapPath("/Images/uploaded/"));
            // create the actual thumbnail image
            System.Drawing.Image thumbnailImage = image.GetThumbnailImage(64, 64, new                                 System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
            // make a memory stream to work with the image bytes
            MemoryStream imageStream = new MemoryStream();
            // put the image into the memory stream
            thumbnailImage.Save(imageStream, System.Drawing.Imaging.Imageformat.Jpeg);
      
            } 
         }

Error message - The name 'ThumbnailCallback' does not exist in the current context.
The type or namespace name 'Imageformat' does not exist in the namespace 'System.Drawing.Imaging' (are you missing an assembly reference?).
Do I need to create a folder to store the thumbnail?

Dani AI

Generated

Short checklist of what to fix (these are the root causes in the original code): implement the required thumbnail callback (or use a different resize path), correct the typo Imageformat -> ImageFormat, pass the full file path (not just the folder) to image-loading APIs, create the thumbnail folder before saving, and always dispose image/stream objects (or use using) to avoid file locks and memory leaks. was right to point out the callback requirement — the callback is tiny but necessary if you call GetThumbnailImage.

Here is a compact, safer pattern that (1) saves the uploaded file with a unique filename, (2) creates a high-quality 64x64 thumbnail using GDI+ (better quality than GetThumbnailImage), (3) writes the thumbnail to disk, and (4) produces a byte[] you can store in a varbinary column.

// example: postedFile = FileUpload1.PostedFile
string ext = Path.GetExtension(postedFile.FileName);
string baseName = Guid.NewGuid().ToString("N").Substring(0,8);
string fileName = baseName + ext;
string imagesFolder = Server.MapPath("~/Images/uploaded/");
string thumbsFolder = Server.MapPath("~/Images/thumbnails/");
Directory.CreateDirectory(imagesFolder);
Directory.CreateDirectory(thumbsFolder);
string imagePath = Path.Combine(imagesFolder, fileName);
postedFile.SaveAs(imagePath);

using (var src = Image.FromFile(imagePath))
using (var thumb = new Bitmap(64, 64))
using (var g = Graphics.FromImage(thumb))
{
    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
    g.CompositingQuality = CompositingQuality.HighQuality;
    g.SmoothingMode = SmoothingMode.HighQuality;
    g.DrawImage(src, 0, 0, 64, 64);
    string thumbPath = Path.Combine(thumbsFolder, baseName + "_thumb" + ext);
    thumb.Save(thumbPath, ImageFormat.Jpeg);
    using (var ms = new MemoryStream())
    {
        thumb.Save(ms, ImageFormat.Jpeg);
        byte[] thumbBytes = ms.ToArray();
        // store thumbBytes into DB using SqlParameter (SqlDbType.VarBinary)
    }
}

If you keep GetThumbnailImage, add this minimal callback somewhere in the page/class:

private bool ThumbnailCallback() { return false; }

Troubleshooting notes: use Path.Combine and Server.MapPath for safe paths; remove duplicate SaveAs calls and pick one unique filename once; ensure the process account has write permission to the thumbnail folder; reference System.Drawing and System.Drawing.Imaging and fix case-sensitive names; prefer FromStream if you want to avoid locking when calling FromFile.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.