바이트 배열을 Base64 이미지로 변환 할 수 있습니다.
public string getBase64Image(byte[] myImage)
{
if (myImage!= null)
{
return "data:image/jpeg;base64," + Convert.ToBase64String(myImage);
}
else
{
return string.Empty;
}
}
이미지 태그는 다음과 같이 표시됩니다
또는 더 큰 이미지 (및 기타 파일 형식)은 다음과 같이됩니다 Generic Handler
public void ProcessRequest(HttpContext context)
{
//check if the querystring 'id' exists
if (context.Request.QueryString["id"] != null)
{
string idnr = context.Request.QueryString["id"].ToString();
//check if the id falls withing length parameters
if (idnr.Length > 0 && idnr.Length < 40)
{
//get the data from the db or other source
byte[] bin = getMyDataFromDB();
//clear the headers
context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.Clear();
context.Response.Buffer = true;
//if you do not want the images to be cached by the browser remove these 3 lines
context.Response.Cache.SetExpires(DateTime.Now.AddMonths(1));
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetValidUntilExpires(false);
//set the content type and headers
context.Response.ContentType = "image/jpeg";
context.Response.AddHeader("Content-Disposition", "attachment; filename=\"myImage.jpg\"");
context.Response.AddHeader("content-Length", bin.Length.ToString());
//write the byte array
context.Response.OutputStream.Write(bin, 0, bin.Length);
//cleanup
context.Response.Flush();
context.Response.Close();
context.Response.End();
}
}
}
이미지 태그를 사용하는 것이 좋습니다에 대한 <img src="data:image/jpeg;base64,/9j/4AAQSkZJRgA...">
: <img src="/Handler1.ashx?id=AB-1234">
실제로 이미지 자체를 src 태그에 포함시킬 수 있는지 전혀 몰랐습니다! 나는 이것을 바로 시도 할 것이다. – rxj
Base64로 변환하면 큰 문자열이 생성됩니다. 나는 보통 50 kb 이상의 이미지를 가진 첫 번째 방법을 사용하지 않는다. – VDWWD
@VDWWD ashx 처리기를 만들 필요가 없습니다. 코드 제공 이미지를 바이트 [] (두 번째 해법)로 처리하면 "일반"getimage.aspx 페이지의 Page_Load()에서 작동합니다. 단지'context.'를'this로 대체하십시오. '(또는 아무것도) –