0

我使用 WebImage 来调整图像大小:

    [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");
        }            
    }

我想使用重定向到默认图像而不是 webimage.write (请参阅捕获部分)。我怎么能做到。

4

1 回答 1

0

你是什​​么意思重定向?.Write() 将直接写入响应流。

在 catch 中,您只需使用默认图像和 .Write() 实例化 WebImage 类。这将像 try 块中的代码一样呈现。

这是 MVC 术语中的一些示例代码。为了完整起见,我尝试流式传输字节内容。希望这可能会有所帮助-

    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;
    }

关键是,WebImage 上可用的大多数方法都返回 WebImage 类型的实例。因此,您也可以随时利用这种灵活性。

于 2018-05-24T14:02:52.483 回答