gpt4 book ai didi

c# - 如何显示存储在本地驱动器或网络驱动器上的图像?

转载 作者:行者123 更新时间:2023-12-02 14:52:14 25 4
gpt4 key购买 nike

我有一个 asp 页面,我必须在其中显示存储在本地磁盘 C: 中的图像,并且在某些情况下来自网络驱动器示例路径:--C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg 我在c#代码后面做了以下代码

Image image = new Image();
image.Height = 150;
image.Width = 150;
string path = @"C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg";//this path will come from database dynamically this is for test only
image.ImageUrl = path;
this.Controls.Add(image);

但是图像没有显示,所以我偶然发现了this SO Question我更新了我的代码如下

对于显示图像的页面

        Image image = new Image();
image.Height = 150;
image.Width = 150;
string path = @"C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg";
image.ImageUrl = "ImageWriter.aspx?path=" + path;
this.Controls.Add(image);

以及代理页面

        Response.ContentType = "image/jpeg"; // for JPEG file
string physicalFileName = Request.QueryString["path"];
Response.WriteFile(physicalFileName);

这工作正常,但我有两个问题

 1) Why the file is accessible from the physical path while proxy from page but other page cannot able to access it ? 
2) And is there any other way to do it ?

任何帮助都会非常感谢。

最佳答案

图像不可用,因为该路径与通过浏览器的 ASP.NET 站点用户没有相对上下文,而该用户可能位于另一台 PC 和网络上。要解决此问题,您需要做的就是创建一个 ASHX 处理程序页面,用于获取服务器本地驱动器或网络上的图像并将它们作为图像提供给浏览器:

    public void ProcessRequest(HttpContext context)
{
string imgName = context.Request.QueryString["n"];
context.Response.ContentType = "image/png";
string path = @"C:\Users\Public\Pictures\Sample Pictures\" + imgName;
Image image = Image.FromFile(path);
image.Save(context.Response.OutputStream, ImageFormat.Png);
}

然后在你的 asp 中只需将图像 url 指向 ashx:

    image.src = "images.ashx?n=penguin.jpg";

关于c# - 如何显示存储在本地驱动器或网络驱动器上的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19272842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com