簡體   English   中英

如何處理/刪除asp.net中imagebutton的損壞的圖像圖標?

[英]How to handle / remove broken image icon of imagebutton in asp.net?

如果圖像損壞,我正在嘗試添加備用圖像,還可以刪除損壞的圖像圖標嗎? 這是我的代碼:

<asp:ImageButton 
    AlternateText = " " 
    onerror = "imgError(this)" 
    ID = "ImageButton111" 
    runat="server" 
    Width = "140" 
    Height = "140" 
    CommandName = "image1" 
    CssClass = "imagetest" 
    CommandArgument = "image"  
    CausesValidation = "false" 
    ImageUrl='<%# "loadImage.ashx?RollNo=" + Eval("RollNO")%>' 
/>



    function imgError(image) {
    image.onerror = "";
    image.src = "~/images/no-hit.gif";
    return true;
}

我認為AlternateText本身是一種內置功能,用於在無法正確加載圖像的情況下設置文本代替圖像。

或者,如果您要替換圖像,請使用此:

<img src="image.gif" onerror="changeImage('alternate_image.gif')">

並在javascript函數中設置備用圖片:

function changeImage(altImage){
$(this).attr('src',altImage.toString());
}

希望能幫助到你 :)

我會擺脫onerror事件,並在您的CodeBehind中實現它。 這樣,如果禁用JavaScript,您仍將獲得所需的結果。 我使用了HttpWebRequest。 它僅檢查HEAD,因此實際上並沒有下載文件,而只是檢查圖像是否可訪問。

   HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ImageButton1.ImageUrl);
    request.Method = "HEAD";

    try
    {
        request.GetResponse();
    }
    catch
    {

        ImageButton1.ImageUrl = "yournewimage.jpg";
    }

您可以像這樣更改數據列表標記,即創建圖像的位置

<%
    string filePath = "loadImage.ashx?RollNo=" + Eval("RollNo");
    if (IsImageValid(filePath))
    {
    %>
      <asp:ImageButton AlternateText=" " ID="ImageButton111" runat="server"
          Width="140" Height="140" CommandName="image1" CssClass="imagetest" CommandArgument = "image"
    CausesValidation="false" ImageUrl='<%# "loadImage.ashx?RollNo=" + Eval("RollNO")%>' />
   <%}
      else
   {%>
     <asp:ImageButton AlternateText=" " ID="ImageButton1" runat="server"
        Width="140" Height="140" CommandName="image1" CssClass="imagetest" CommandArgument="image"
         CausesValidation="false" ImageUrl="~/images/no-hit.gif" />
  <%} %>

現在您要做的是,如果圖像損壞,則創建另一個圖像

和IsImageValid函數可以這樣定義

public bool IsImageValid(string filename)
{
    try
    {
        System.Drawing.Image newImage = System.Drawing.Image.FromFile(filename);
    }
    catch (OutOfMemoryException ex)
    {
        // Image.FromFile will throw this if file is invalid.
        // Don't ask me why.
        return false;
    }
    return true;
}

所有這些都可以在OnItemDataBound事件中完成,甚至更加輕松。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM