图像.从文件"File Not Found" 当文件存在时



我有一个文件存储在我网站的目录中。 当我尝试使用 image.fromfile 访问该文件时,会抛出一个异常,指出该文件不存在。 但是,当我使用完全相同的路径访问完全相同的文件但将其加载到图像控件中时,图像会完美加载,验证它是否存在。

引发"找不到文件"异常的代码是:

Private Sub btnCombine_Click(sender As Object, e As EventArgs) Handles btnCombine.Click
Dim BMCanvas As Bitmap     'the "canvas" to draw on
Dim BackgroundTemplate As Image     'the background image

Dim img1Overlay As Bitmap   'the character image
BackgroundTemplate = Image.FromFile("~/Account/Images/Blue 1-02.jpg")   'Template Background Image
img1Overlay = Image.FromStream(FileUpload1.FileContent)  'First overlay image
BMCanvas = New Bitmap(500, 647)    'new canvas
Using g As Graphics = Graphics.FromImage(BMCanvas)
g.DrawImage(BackgroundTemplate, 0, 0, 500, 647)  'Fill the convas with the background image
g.DrawImage(img1Overlay, 50, 50, 100, 100)  'Insert the overlay image onto the background image
End Using
'Setup a path to the destination for the composite image
Dim folderPath As String = Server.MapPath("~/OutFiles/")
'Create a directory to store the composite image if it does not already exist.
If Not Directory.Exists(folderPath) Then
'If Directory (Folder) does not exists Create it.
Directory.CreateDirectory(folderPath)
End If
'Temporarily save the file as jpeg.
BMCanvas.Save(folderPath & "Temp1.jpg", Imaging.ImageFormat.Jpeg)

'View the resulting composite image in image control.
Image1.ImageUrl = folderPath & "Temp1.jpg"
BMCanvas.Dispose()
End Sub

验证图像确实在目录中并成功显示图像的代码是:

Private Sub cboRole_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboRole.SelectedIndexChanged
If cboRole.SelectedIndex = 1 Then
Image1.ImageUrl = "~/Account/Images/Blue 1-02.jpg"
End If
End Sub

我不知道为什么一种方式有效而另一种方式无效。

我也尝试了以下代码但没有成功:

'Another way to read the image files
Image = File.ReadAllBytes(Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "~/Account/Images/Blue 1-02.jpg")))

好的,您问题的第二部分("为什么它与 ImageURL 一起工作?"(的答案位于文档中

报价:

使用 ImageUrl 属性指定要在其中显示的图像的 URL 图像控件。您可以使用相对 URL 或绝对 URL。一个 相对 URL 将图像的位置与 未在服务器上指定完整路径的网页。路径是 相对于网页的位置。这使得移动更容易 将整个站点复制到服务器上的另一个目录,而不进行更新 代码。绝对 URL 提供完整的路径,因此移动 站点到另一个目录需要您更新代码。

它(图像控件(已经具有"映射"相对于网页文件夹的路径的嵌入功能。

在代码中使用路径时,如果没有控件(如在 Image.FromFile 中(,则需要使用 Server.MapPath 确保路径正确映射

正如您在创建目录的代码中所做的那样。

不能有来自相对 url 的图像。 要以 System.Drawing.Image 的形式获取图像,您需要从这样的物理路径获取它们(在您的情况下(

Dim image As System.Drawing.Image = System.Drawing.Image.FromFile(HttpContext.Current.Request.PhysicalApplicationPath & "AccountImagesBlue 1-02.jpg") 'Server.MapPath("~/Account/Images/Blue 1-02.jpg")) 

最新更新