【问题标题】:How can I redirect to default image use WebImage in MVC如何在 MVC 中重定向到默认图像使用 WebImage
【发布时间】:2018-05-24 12:07:03
【问题描述】:

我使用 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(请参阅捕获部分)。我该怎么做。

【问题讨论】:

    标签: asp.net model-view-controller webimage


    【解决方案1】:

    重定向是什么意思? .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 类型的实例。因此,您也可以随时利用这种灵活性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-27
      • 1970-01-01
      相关资源
      最近更新 更多