Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to use WPF assemblies in a web app?

I have an ASP.NET MVC 2 app targeting .NET 4 that needs to be able to resize images on the fly and write them to the response.

I have code that does this and it works. I am using System.Drawing.dll.

However, I want to enhance my code so that not only am I resizing the image, but I am dropping it from 24bpp down to 4bit grayscale. I could not, for the life of me, find code on how to do this with System.Drawing.dll.

But I did find a bunch of WPF stuff. This is my working/sample code (runs in LinqPad).

// Load the original 24 bit image
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.UriSource = new Uri(@"C:\Temp\Resized\18_appa2_015.png", UriKind.Absolute);
//bitmapImage.DecodePixelWidth = 600;
bitmapImage.EndInit();

// Create the destination image
var formatConvertedBitmap = new FormatConvertedBitmap();
formatConvertedBitmap.BeginInit();
formatConvertedBitmap.Source = bitmapImage;
formatConvertedBitmap.DestinationFormat = PixelFormats.Gray4;
formatConvertedBitmap.EndInit();

// Encode and dump the image to disk
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(formatConvertedBitmap));
using (var fileStream = File.Create(@"C:\Temp\Resized\18_appa2_015_s2.png"))
{
    encoder.Save(fileStream);
}

It uses System.Xaml.dll, WindowsBase.dll, PresentationCore.dll, and PresentationFramework.dll. The namespaces used are: System.Windows.Controls, System.Windows.Media, and System.Windows.Media.Imaging.

Is there any problem using these namespaces in my web application? It doesn't seem right.

If anyone knows how to drop the bit depth without all this WPF stuff (which I barely understand, BTW) I would be thrilled to see that too.

like image 801
Chris Avatar asked Mar 11 '10 05:03

Chris


2 Answers

No problem. You can easily use WPF for image manipulation from within an ASP.NET web site. I've used WPF behind the scenes within a web site several times before, and it works great.

The one issue I did run into is that many parts of WPF insist the calling threads be STA threads. If your web site uses MTA threads instead you will get an error telling you that WPF needs STA threads. To fix this, use the STAThreadPool class I posted in this answer.

like image 160
Ray Burns Avatar answered Nov 11 '22 19:11

Ray Burns


My understanding (and I can't find a citation right now) is that this is officially not supported. However, in practice, it seems to work pretty well and you would not be alone in using these libraries in a Web app. Also, even if you can find a way of doing this with System.Drawing, I believe that officially that's not supported in the Web environment either -- though it is more widely used in that environment than WPF, which gives you an extra level of reassurance.

like image 2
itowlson Avatar answered Nov 11 '22 19:11

itowlson