How can I redirect to default image use WebImage in MVC

42 views Asked by At

I use WebImage for resize images:

    [ImageOutputCache(Duration = 3000, Location = System.Web.UI.OutputCacheLocation.Client)]
    public void GetPic(string fn, int? w, int? h)
    {            
        try
        {
            if (w > 1920) { w = 1920; }
            if (h > 1080) { h = 1080; }
            WebImage wi = new WebImage(@"~/img/" + fn);
            if (!h.HasValue)
            {
                Single ratio = (Single)wi.Width / (Single)wi.Height;
                h = (int)Math.Ceiling(wi.Width / ratio);
            }

            wi
                    .Resize(w.Value + 1, h.Value + 1, true, true) // Resizing the image to 100x100 px on the fly...
                    .Crop(1, 1) // Cropping it to remove 1px border at top and left sides (bug in WebImage)
                    .Write();
        }
        catch
        {
            //new WebImage(@"~/img/default.jpg").Write();
            //Redirect(@"~/img/default.jpg");
        }            
    }

I want to use redirect to default image instead webimage.write (see catch section). how i can do it.

1

There are 1 answers

0
mtv On

What do you mean redirect? .Write() is going to write to the response stream directly.

In catch you would simply instantiate WebImage class with the default image and .Write() it. That would be rendered just like the code inside try block.

Here is some sample code in MVC terms. For completeness I tried to stream the byte content. Hope this might help -

    public ActionResult GetPic()
    {
        int? w = 500;
        int? h = 500;
        FileStreamResult fsr = null;
        MemoryStream ms = null;
        try
        {
            if (w > 200) { w = 200; }
            if (h > 200) { h = 200; }
            WebImage wi = new WebImage(@"C:\Temp\MyPic.JPG");
            if (h.HasValue)
            {
                Single ratio = (Single)wi.Width / (Single)wi.Height;
                h = (int)Math.Ceiling(wi.Width / ratio);

                var imageData = wi.Resize(w.Value + 1, h.Value + 1, true, true)
                    .Crop(1, 1)
                    .Write().GetBytes();                    

                fsr = new FileStreamResult(ms, "jpg");
            }
        }
        catch
        {
            byte[] imageData = new WebImage(@"C:\Temp\Star.JPG").GetBytes();
            ms = new MemoryStream(imageData);
            fsr = new FileStreamResult(ms, "jpg");
        }

        return fsr;
    }

The point is, most of the methods available on WebImage return an instance of type WebImage. So, you can always take advantage of that flexibility too.