Sharing image resources between WPF and ASP.NET

A question about sharing images between WPF and ASP.NET was asked in a thread at StackOverflow.com (http://stackoverflow.com/questions/12882628/). This sample explains the solution in a more detailed way than on StackOverflow.

A library project contains two images, which have to be shared. First the images have to be declared as resource, so choose properties and Build Action with “Resource”.

The WPF application loads the images directly with the source attribute, which is set after the following scheme: /<LibraryName>;component/<Folder>/<ImageName>

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <Image Name="image1" Grid.Column="0" Grid.Row="0" Source="/MyResourceClass;component/Resources/Image1.png" />
    <Image Name="image2" Grid.Column="0" Grid.Row="1" Source="/MyResourceClass;component/Resources/Image2.png" />
</Grid>

The result is a boring simple application, but with two images.

The ASP.NET application uses a generic handler to load, convert and display the images. The html itself has only to declare a simple image with a reference to the generic handler. A get parameter is used to set which image will be loaded.

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = &quot;image/jpg&quot;;
    context.Response.Clear();

    ResourceManager rm = new ResourceManager(&quot;MyResourceClass.MainResources&quot;, Assembly.Load(&quot;MyResourceClass&quot;));

    Bitmap image = (Bitmap)rm.GetObject(context.Request.QueryString[&quot;imageid&quot;]);
    if (image != null)
    {
        image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
    }
}

The result is another simple boring webpage, but with images.

The solution can be found on github.

Advertisements
This entry was posted in ASP.NET, C#, Development, WPF and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s