我想创建和图像处理程序,将调整图像大小并将图像返回到我的应用程序

时间:2016-05-19 11:59:30

标签: angularjs asp.net-mvc image handler webapi2

This is the same question asked before and the answer is also verified but in My Project I am using WebApi 2 and want return image from Ihttpactionresult

我已经搜索了很多并完成了一些代码,如果我做得对,我不知道。

我也查看了ImageReizer,但它将已调整大小的图像保存在文件夹中。我不想保存图片。

这是我的控制器操作

  [HttpGet]
    [Route("GetFile")]
    public IHttpActionResult GetFile(string filename, int w = 0, int h = 0)
    {
        //string filePath = "fdsafsa";
        //int width = 0;
        //var fileStream = File.Open("/ProjectFiles", FileMode.Open);
        //var content = new StreamContent(fileStream);
        //content.Headers.ContentType = new MediaTypeHeaderValue("png");

        var imageFile = HttpContext.Current.Server.MapPath(@filename);
        if(File.Exists(imageFile))
        {
            var srcImage = Image.FromFile(imageFile);
            var newImage = new Bitmap(w, h);
            var graphics = Graphics.FromImage(newImage);
            var stream = new MemoryStream();
            graphics.SmoothingMode = SmoothingMode.AntiAlias;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
            graphics.DrawImage(srcImage, new Rectangle(0, 0, w, h));
            newImage.Save(stream, ImageFormat.Png);
            //var content = new StreamContent(stream);

            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new ByteArrayContent(stream.ToArray());
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");

            return Ok(result);
        }

这是我要渲染图像的html

<img src="/api/Public/GetFile?filename=/ProjectFiles/Project_2087/art-therapy-career2_73937984-7e03-4067-91bf-2dd4fc10b328.jpg&w=100&h=100" alt="image" />

如何在不将调整大小图像存储在服务器上的情况下动态显示已调整大小的图像。我不想保存调整大小的图像。

我很快就会得到帮助。

感谢您的帮助。

另一种方法......

 [HttpGet]
    [Route("GetFileStream")]
    public IHttpActionResult GetFileStream(string filename, int w = 0, int h = 0)
    {
        var imagePath = HttpContext.Current.Server.MapPath(@filename);
        var result = getResizedImage(imagePath, w, h);
        return Ok(result);
    }


 byte[] getResizedImage(String path, int width, int height)
    {
        Bitmap imgIn = new Bitmap(path);
        double y = imgIn.Height;
        double x = imgIn.Width;

        double factor = 1;
        if (width > 0)
        {
            factor = width / x;
        }
        else if (height > 0)
        {
            factor = height / y;
        }
        System.IO.MemoryStream outStream = new System.IO.MemoryStream();
        Bitmap imgOut = new Bitmap((int)(x * factor), (int)(y * factor));
        Graphics g = Graphics.FromImage(imgOut);
        g.Clear(Color.White);

        g.DrawImage(imgIn, new Rectangle(0, 0, (int)(factor * x), (int)(factor * y)), new Rectangle(0, 0, (int)x, (int)y), GraphicsUnit.Pixel);

        imgOut.Save(outStream, getImageFormat(path));
        return outStream.ToArray();
    }

**

这是带有Mvc的工作代码

**

这是我发现为Simple Mvc Application

工作的代码

行动

public ActionResult Thumb(string filename = "Azalea.jpg", int w = 0, int h = 0)
    {
        string path = Path.Combine(Server.MapPath("~/images2"), filename);
        //Bitmap bitmap = new Bitmap(filepath);
        //if (bitmap == null)
        //{
        //    return new EmptyResult();
        //}

        //MemoryStream ms = new MemoryStream();
        //bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        Bitmap imgIn = new Bitmap(path);
        double y = imgIn.Height;
        double x = imgIn.Width;

        double factor = 1;
        if (w > 0)
        {
            factor = w / x;
        }
        else if (h > 0)
        {
            factor = h / y;
        }
        System.IO.MemoryStream outStream = new System.IO.MemoryStream();
        Bitmap imgOut = new Bitmap((int)(x * factor), (int)(y * factor));
        Graphics g = Graphics.FromImage(imgOut);
        g.Clear(Color.White);

        g.DrawImage(imgIn, new Rectangle(0, 0, (int)(factor * x), (int)(factor * y)), new Rectangle(0, 0, (int)x, (int)y), GraphicsUnit.Pixel);

        imgOut.Save(outStream, getImageFormat(path));
        outStream.Seek(0, SeekOrigin.Begin);
        FileStreamResult fileStreamResult = new FileStreamResult(outStream, "image/png");
        return fileStreamResult;
    }

在cshtml页面

   <img src="~/Home/Thumb/@Model.ImageName?w=700&h=300" alt="image" />

如何使用此功能使用Web Api2?

长时间搜索后回答我的问题。请改善此

  [HttpGet]
    [Route("GetFileStream")]
    public IHttpActionResult GetFileStream(string filename, int w = 0, int h = 0)
    {
        var imagePath = HttpContext.Current.Server.MapPath(@filename);
        return new FileResult(imagePath, w, h, "image/jpeg");
    }

    public class FileResult : IHttpActionResult
    {
        private readonly string filePath;
        private readonly string contentType;
        private readonly int width;
        private readonly int height;

        public FileResult(string filePath, int width, int height, string contentType = null)
        {
            this.filePath = filePath;
            this.contentType = contentType;
            this.width = width;
            this.height = height;
        }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            return Task.Run(() =>
            {
                var result = getResizedImage(filePath, width, height);
                var response = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ByteArrayContent(result)
                    //Content = new StreamContent(File.OpenRead(filePath))
                };

                var contentType = this.contentType ?? MimeMapping.GetMimeMapping(Path.GetExtension(filePath));
                response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);

                return response;
            }, cancellationToken);
        }
    }

  static byte[] getResizedImage(String path, int width, int height)
    {
        Bitmap imgIn = new Bitmap(path);
        double y = imgIn.Height;
        double x = imgIn.Width;

        double factor = 1;
        if (width > 0)
        {
            factor = width / x;
        }
        else if (height > 0)
        {
            factor = height / y;
        }
        System.IO.MemoryStream outStream = new System.IO.MemoryStream();
        Bitmap imgOut = new Bitmap((int)(x * factor), (int)(y * factor));
        Graphics g = Graphics.FromImage(imgOut);
        g.Clear(Color.White);

        g.DrawImage(imgIn, new Rectangle(0, 0, (int)(factor * x), (int)(factor * y)), new Rectangle(0, 0, (int)x, (int)y), GraphicsUnit.Pixel);

        imgOut.Save(outStream, getImageFormat(path));
        //outStream.Seek(0, SeekOrigin.Begin);
        //System.Web.Mvc.FileStreamResult fileStreamResult = new System.Web.Mvc.FileStreamResult(outStream, "image/png");
        //return fileStreamResult;
        return outStream.ToArray();
    }

    string getContentType(String path)
    {
        switch (Path.GetExtension(path))
        {
            case ".bmp": return "Image/bmp";
            case ".gif": return "Image/gif";
            case ".jpg": return "Image/jpeg";
            case ".png": return "Image/png";
            default: break;
        }
        return "";
    }

    static ImageFormat getImageFormat(String path)
    {
        switch (Path.GetExtension(path))
        {
            case ".bmp": return ImageFormat.Bmp;
            case ".gif": return ImageFormat.Gif;
            case ".jpg": return ImageFormat.Jpeg;
            case ".png": return ImageFormat.Png;
            default: break;
        }
        return ImageFormat.Jpeg;
    }

请帮助改进此答案,

谢谢, Sanuj

1 个答案:

答案 0 :(得分:0)

您可以将byteArray传递给View,然后使用以下内容:

创建图像模型:

public class ImageData
{
    public string Name { get; set; }
    public byte[] Content { get; set; }
    . . .
}

然后在控制器中分配并将模型返回到View():

@{
    string imageBase = Convert.ToBase64String(Model.ImageContent);
    string imageSource = string.Format("data:image/gif;base64,{0}", imageBase);
}
<img src="@imageSource" alt="@Model.ImageName" width="100" height="100" />