Одед верен, я бы использовал обработчик для возврата изображения. Пример ниже:
Класс обработчика :
public class ImageHandler : IHttpHandler
{
public void ProcessRequest( HttpContext context )
{
try
{
String Filename = context.Request.QueryString[ "FileName" ];
if ( !String.IsNullOrEmpty( Filename ) )
{
// Read the file and convert it to Byte Array
string filename = context.Request.QueryString[ "FileName" ];
string contenttype = "image/" + Path.GetExtension( Filename.Replace( ".", "" ) );
FileStream fs = new FileStream( filename, FileMode.Open, FileAccess.Read );
BinaryReader br = new BinaryReader( fs );
Byte[] bytes = br.ReadBytes( ( Int32 ) fs.Length );
br.Close();
fs.Close();
//Write the file to response Stream
context.Response.Buffer = true;
context.Response.Charset = "";
context.Response.Cache.SetCacheability( HttpCacheability.NoCache );
context.Response.ContentType = contenttype;
context.Response.AddHeader( "content-disposition", "attachment;filename=" + filename );
context.Response.BinaryWrite( bytes );
context.Response.Flush();
context.Response.End();
}
}
catch ( Exception )
{
throw;
}
}
/// <summary>
/// Gets whether the handler is reusable
/// </summary>
public bool IsReusable
{
get { return true; }
}
}
Затем я добавил общий метод Page для использования обработчика:
/// <summary>
/// Gets the image handler query
/// </summary>
/// <param name="ImagePath">The path to the image</param>
/// <returns>Image Handler Query</returns>
protected string GetImageHandlerQuery(string ImagePath)
{
try
{
if (ImagePath != string.Empty)
{
string Query = String.Format("..\\Handlers\\ImageHandler.ashx?Filename={0}", ImagePath);
return Query;
}
else
{
return "../App_Themes/Dark/Images/NullImage.gif";
}
}
catch (Exception)
{
throw;
}
}
И, наконец, использовать в ASPX:
<asp:ImageButton ID="btnThumbnail" runat="server" CommandName="SELECT" src='<%# GetImageHandlerQuery((string)Eval("ImageThumbnail200Path")) %>'
ToolTip='<%#(string) Eval("ToolTip") %>' Style="max-width: 200px; max-height: 200px" />
или, если вы хотите использовать в Code Behind:
imgPicture.ImageUrl = this.GetImageHandlerQuery( this.CurrentPiecePicture.ImageOriginalPath );
Очевидно, что вам не нужен метод страницы, и вы можете напрямую вызывать обработчик, но это может быть полезно поместить в класс вашей базовой страницы.