简体   繁体   中英

how to convert HttpPostedFile to thumbnail file. .net C#

I have been try to convert files to smaller file to insert database.

I try to covert images/HttpPostedFile to thumbnail file.

<form id="form1" runat="server">
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <br />
    <asp:Button ID="btnGenerate" OnClick="GenerateThumbnail" runat="server" Text="Generate Thumbnail" />
    <hr />
    <asp:Image ID="Image2" runat="server" Visible="false" />

</form>

and

protected void GenerateThumbnail(object sender, EventArgs e)
{        
    HttpPostedFile postedFile = FileUpload1.PostedFile;
    string filename = Path.GetFileName(postedFile.FileName);
    string fileExtension = Path.GetExtension(filename);
    System.Drawing.Image image = System.Drawing.Image.FromFile(filename);
    using (System.Drawing.Image thumbnail = image.GetThumbnailImage(100, 100, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero))
    {
        using (MemoryStream memoryStream = new MemoryStream())
        {
            thumbnail.Save(memoryStream, ImageFormat.Png);
            Byte[] bytes = new Byte[memoryStream.Length];
            memoryStream.Position = 0;
            memoryStream.Read(bytes, 0, (int)bytes.Length);
            string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
            Image2.ImageUrl = "data:image/png;base64," + base64String;
            Image2.Visible = true;
        }
    }
}

public bool ThumbnailCallback()
{
    return false;
}

This part is causing error

HttpPostedFile postedFile = FileUpload1.PostedFile;
string filename = Path.GetFileName(postedFile.FileName);
string fileExtension = Path.GetExtension(filename);
System.Drawing.Image image = System.Drawing.Image.FromFile(filename);

how can I convert HttpPostedFile to thumbnail file?

You haven't saved the file to disk so when you try to create the image from a file, it fails. Instead, create the image directly from the stream.

var image = System.Drawing.Image.FromStream(postedFile.InputStream);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM