Thursday, May 07, 2009

Photoviewer

Today I needed to write a pop up form that would show any image without any extra IE (or Firefox, Chrome, Safari, etc.) toolbars, etc. To get a web form to display an arbitrary image, I have a simple page that takes the URL of the image in the query string. The web form takes that string and uses it to set ImageUrl of an asp.image control.

photoviewer.aspx:
<%@ Page Language="C#" EnableViewState="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">    private void Page_Load()
    {        string file = Request.QueryString["file"];
        if (file != null)
            myImage.ImageUrl = Server.UrlDecode(file);
    }
</script>
<html>
<head>
    <title>My Image Viewer</title>
</head><body>
    <form id="Form1" method="post" runat="server">
    <table style="border:0;">
        <tr>
            <td>
                <asp:Image runat="server" ID="myImage" EnableViewState="false" />
            </td>    
        </tr>
        <tr>
            <td>
                <input type="button" onclick="javascript: window.close();" 
                    value="close" />
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

To get rid of extra browser features and to size the popup, I call window.open() I set the height and width to values that will ensure that I have enough room for the image (I can use to get the dimensions of an image and add some buffer around the image so the popup isn’t all picture). I suppress status, toolbar, menubar. Location and scrollbars by setting them all to “0”.

feature_win.js
// declared outside of the scope of the function so it will persist on the page:
var newWindow;
function featureWin(height, width, url)
{
    var lHeight = height;
    var lWidth = width;
    
    if (newWindow && !newWindow.closed) 
    {
      newWindow.close()
    }
    newWindow = window.open(url, null, 'height=' + height +  
       ',width=' + width + ',status=0,toolbar=0,menubar=0,location=0,scrollbars=0');
}

Here we put it all together.

default.html
<html>
<head>
    <title>Test My Image Viewer</title>
    <script type="text/javascript" src="feature_win.js"></script>
</head>
<body>
<a href="javascript: featureWin(825, 1050, 'photoviewer.aspx?file=Garden.jpg');">
    Garden</a>
</body>
</html>

No comments: