Resize images with MVC 6 on Ubuntu running ASP.NET

2019-09-11 02:53发布

问题:

How can I re-size an image in ASP.NET 5, MVC 6, DNX451, with MONO, running on Ubuntu?

I have been unable to work this out, as the standard components that I have used such as ImageProcessor and ImageResizer.NET seem not to be working.

回答1:

check out this cross platform library: https://github.com/JimBobSquarePants/ImageSharp

sample usage:

using (FileStream stream = File.OpenRead("foo.jpg"))
using (FileStream output = File.OpenWrite("bar.jpg"))
{
    Image image = new Image(stream);
    image.Resize(image.Width / 2, image.Height / 2)
         .Greyscale()
         .Save(output);
}


回答2:

I am currently developing a website in DNX 4.5.1 (ASP.NET 5) and MVC 6, which is meant to be hosted on an Ubuntu server.

Recently I ran in to issues with re-sizing images, so I had to think out of the box. In my case, it was not necessary, to re-size images on my development environment, so I focused on how to handle this on my upcoming prod environment.

The solution was to use ImageMagick, which is a very nice little piece of software for Linux.

This is how I solved it:

if (_hostingEnvironment.IsProduction())
{
        var command = "-c 'convert " + filePath + " -resize 960x960 -quality 70 " + filePath + "'";

        Process proc = new System.Diagnostics.Process();
        proc.StartInfo.FileName = "/bin/bash";
        proc.StartInfo.Arguments = command;
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.RedirectStandardOutput = false;
        proc.Start();
}

So this works by uploading the file to some folder, in my case a temporary folder, then I execute the convert command. I overwrite the same file with the conversion parameters that I need in my project. You can use more parameters, if you want larger images or better quality.

This is a nice solution, but as I said, I have only focused on making this work on Ubuntu, which will be my production environment, and therefor it is encapsulated in an if clause, checking whether I am on prod or not, but a similar approach could probably also be possible in Windows environments, but I would rather go for some standard component to make that work.