locked
Resizing and creating a thunbnail from uploaded image RRS feed

  • Question

  • User-544697354 posted

    I am using the FileUpload control to upload images to a folder on my server and also store the location in a db table. How can I: 1) check to make sure the files being uploaded are jpgs 2) resize the image to be a thumbnail and also larger at 150x150. Here is my code for the upload

    protected void btnUpload_Click(object sender, EventArgs e)

    {

    try

    {

    DALBWLoginDataContext db = new DALBWLoginDataContext();

    string path = "~\\Assets\\RepImages\\" + Session["UserID"].ToString() + ".jpg";

    UserImage um = db.UserImages.SingleOrDefault(a => a.nUserID == Convert.ToInt32(Session["UserID"]));if (um != null)

    {

    if (File.Exists(path))

    {

    File.Delete(path);

    }

    db.UserImages.DeleteOnSubmit(um);

    db.SubmitChanges();

    }

     

    if (FileUpload1.HasFile)

    {

    string filepath = FileUpload1.PostedFile.FileName;

    string pat = @"\\(?:.+)\\(.+)\.(.+)";

    Regex r = new Regex(pat);

    Match m = r.Match(filepath);

    string file_ext = m.Groups[2].Captures[0].ToString();

    string filename = m.Groups[1].Captures[0].ToString();

    string file = filename + "." + file_ext;string FileToResize = Server.MapPath("~/images/1.jpg");

     

    FileUpload1.PostedFile.SaveAs(Server.MapPath(
    "~\\Assets\\RepImages\\") + Session["UserID"].ToString() + ".jpg");

     

    StoreImagePath(path);

    dvImage.DataBind();

    lblStatus.Text =
    "Received " + FileUpload1.FileName;

    }

    else

    {

    lblStatus.Text =
    "You have not selected a valid upload file.";

    }

    }

    catch (Exception)

    {

    throw;

    }

    }

    private void StoreImagePath(string path)

    {

    DALBWLoginDataContext db = new DALBWLoginDataContext();UserImage img = new UserImage();

    img.sImageURL = path;

    img.nUserID = Convert.ToInt32(Session["UserID"]);

    img.nssiCorpID = Convert.ToInt32(Session["ssiCorpID"]);

    db.UserImages.InsertOnSubmit(img);

    db.SubmitChanges();

    }

    Tuesday, January 6, 2009 11:45 AM

Answers

  • User-627724879 posted

    This is what I put to gether a few years ago and still use, http://www.codeplex.com/ExImageResizer.

    You can also set a filter to limit the file types on the client, but you should always check on the server:

                            <tr>
                                <td align="left">
                                    Picture
                                </td>
                                <td align="left">
                                    <asp:FileUpload ID="fPicture" runat="server" CssClass="formField" />
                                    <asp:RegularExpressionValidator runat="server" ID="rvfPicture" ControlToValidate="fPicture"
                                        ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpg|.JPG|.png|.PNG|.gif|.GIF)$"
                                        ErrorMessage="You can only upload .jpg, .gif or .png image types." />
                                </td>
                            </tr>

     

        Private _UploadedFileName As String = String.Empty
        Private ReadOnly Property UploadedFileName() As String
            Get
                If String.IsNullOrEmpty(_UploadedFileName) Then
                    If fPicture.HasFile Then
                        _UploadedFileName = HttpUtility.UrlDecode(Path.GetFileName(fPicture.FileName)).Replace(" ", "-")
                    ElseIf IsNothing(ViewState("PictureFileName")) = False Then
                        _UploadedFileName = ViewState("PictureFileName").ToString
                    End If
                End If
                Return _UploadedFileName
            End Get
        End Property

        Private _PhotoExtension As String = String.Empty
        Private ReadOnly Property PhotoExtension() As String
            Get
                If String.IsNullOrEmpty(_PhotoExtension) Then
                    _PhotoExtension = Path.GetExtension(fPicture.FileName)
                End If
                Return _PhotoExtension
            End Get
        End Property

            If fPicture.HasFile Then

                If PhotoExtension.ToLower.Contains("jpg") = False And _
                    PhotoExtension.ToLower.Contains("gif") = False Then
                    Response.Write("<B>You can Only Upload JPGs or GIFs</B>")
                    Exit Sub
                End If

    ........

                lgi.StoreImage(GalleryHelper.GetAlbumThumbNailsDirectory( _
                    ddlAlbums.SelectedItem.Text), _
                    Path.GetFileName(lThumbnailFileName), _
                    lOriginalFileName, _
                    Convert.ToInt32(txtWidth.Text), _
                    Convert.ToInt32(txtHeight.Text))
     

    ....... 

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, January 6, 2009 12:40 PM