我一直在尝试将文件转换为较小的文件以插入数据库。
我尝试将图像/ HttpPostedFile转换为缩略图文件。
<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>
和
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;
}
此部分导致错误
HttpPostedFile postedFile = FileUpload1.PostedFile;
string filename = Path.GetFileName(postedFile.FileName);
string fileExtension = Path.GetExtension(filename);
System.Drawing.Image image = System.Drawing.Image.FromFile(filename);
如何将HttpPostedFile转换为缩略图文件?
答案 0 :(得分:0)
您尚未将文件保存到磁盘,因此当您尝试从文件创建映像时,它会失败。而是直接从流中创建图像。
var image = System.Drawing.Image.FromStream(postedFile.InputStream);