一旦图像上传,如何将单个图像制作成不同(优化)尺寸?

时间:2012-09-25 08:04:39

标签: image image-processing asp.net-mvc-4

我已经服用了 这个,因为我发送给你只是看一下,请一次,这是这是正确的方式来做这项工作

 UploadController  class file


 public class UploadController : ApiController
    {


    public async Task<HttpResponseMessage> Post()
    {
        if (!Request.Content.IsMimeMultipartContent("form-data"))
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        var uploadFolder = HostingEnvironment.MapPath("~/app_data");
        uploadFolder = Path.Combine(uploadFolder, DateTime.Now.ToString("yyyyMMddhhmmssfff"));
        Directory.CreateDirectory(uploadFolder);
        var streamProvider = new PreserveFilenameMultipartFileStreamProvider(uploadFolder);

        var parts = await Request.Content.ReadAsMultipartAsync(streamProvider);
        foreach (var uploadedFile in Directory.GetFiles(uploadFolder))
        {
            var thumbnail = Path.Combine(uploadFolder, "thumb-" + Path.GetFileName(uploadedFile));
            var medium = Path.Combine(uploadFolder, "medium-" + Path.GetFileName(uploadedFile));
            var large = Path.Combine(uploadFolder, "large-" + Path.GetFileName(uploadedFile));
            ImageTools.Resize(uploadedFile, thumbnail, 100, 100);
            ImageTools.Resize(uploadedFile, medium, 200, 200);
            ImageTools.Resize(uploadedFile, large, 300, 300);
        }

        return Request.CreateResponse(HttpStatusCode.Accepted);

我在模型文件夹

中为imagetools单独创建了一个文件
 public class imageTools
    {
        public static void Resize(string original, string output, int width, int height)
        {
            using (var image = Image.FromFile(original))
            using (var thumbnail = new Bitmap(width, height))
            using (var graphics = Graphics.FromImage(thumbnail))
            {
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                graphics.CompositingQuality = CompositingQuality.HighQuality;

                graphics.DrawImage(image, 0, 0, width, height);

                ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
                EncoderParameters encoderParameters;
                encoderParameters = new EncoderParameters(1);
                encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
                thumbnail.Save(output, info[1], encoderParameters);
            }
        }
    }

我又拿了一个名为

的文件
  PreserveFilenameMultipartFileStreamProvider




    public class PreserveFilenameMultipartFileStreamProvider : MultipartFileStreamProvider
    {
        public PreserveFilenameMultipartFileStreamProvider(string rootPath)
            : base(rootPath)
        {
        }

        public override string GetLocalFileName(HttpContentHeaders headers)
        {
            return headers.ContentDisposition.FileName.Replace("\"", "");
        }
    }

最后是我的布局页面

     @using (Html.BeginRouteForm("DefaultApi", new { httproute = "", controller = "images" }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="image" multiple="multiple" accept="image/*" />
    <button type="submit">Upload</button>
}

1 个答案:

答案 0 :(得分:2)

您可以使用ImageResizer package。或者你也可以implement image resizing yourself


更新:这是一个可用于调整Web API控制器中上传图像大小的示例。

您可以首先编写一个将使用GDI +的Resize方法,如我之前链接到的文章所示:

public static class ImageTools
{
    public static void Resize(string original, string output, int width, int height)
    {
        using (var image = Image.FromFile(original))
        using (var thumbnail = new Bitmap(width, height))
        using (var graphics = Graphics.FromImage(thumbnail))
        {
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.SmoothingMode = SmoothingMode.HighQuality;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
            graphics.CompositingQuality = CompositingQuality.HighQuality;

            graphics.DrawImage(image, 0, 0, width, height);

            ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
            EncoderParameters encoderParameters;
            encoderParameters = new EncoderParameters(1);
            encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
            thumbnail.Save(output, info[1], encoderParameters);
        }
    }
}

然后是自定义MultipartFileStreamProvider,它将保留最初上传的文件名:

public class PreserveFilenameMultipartFileStreamProvider : MultipartFileStreamProvider
{
    public PreserveFilenameMultipartFileStreamProvider(string rootPath): base(rootPath)
    {
    }

    public override string GetLocalFileName(HttpContentHeaders headers)
    {
        return headers.ContentDisposition.FileName.Replace("\"", "");
    }
}

最后你可以有一个API控制器来接收上传的图像,将它们存储在App_Data文件夹中,并通过调整大小来生成不同的格式:

public class ImagesController : ApiController
{
    public async Task<HttpResponseMessage> Post()
    {
        if (!Request.Content.IsMimeMultipartContent("form-data"))
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        var uploadFolder = HostingEnvironment.MapPath("~/app_data");
        uploadFolder = Path.Combine(uploadFolder, DateTime.Now.ToString("yyyyMMddhhmmssfff"));
        Directory.CreateDirectory(uploadFolder);
        var streamProvider = new PreserveFilenameMultipartFileStreamProvider(uploadFolder);

        await Request.Content.ReadAsMultipartAsync(streamProvider);
        foreach (var uploadedFile in Directory.GetFiles(uploadFolder))
        {
            var thumbnail = Path.Combine(uploadFolder, "thumb-" + Path.GetFileName(uploadedFile));
            var medium = Path.Combine(uploadFolder, "medium-" + Path.GetFileName(uploadedFile));
            var large = Path.Combine(uploadFolder, "large-" + Path.GetFileName(uploadedFile));
            ImageTools.Resize(uploadedFile, thumbnail, 100, 100);
            ImageTools.Resize(uploadedFile, medium, 200, 200);
            ImageTools.Resize(uploadedFile, large, 300, 300);
        }

        return Request.CreateResponse(HttpStatusCode.Accepted);
    }
}

最后,您可以拥有一个允许用户上传图片的HTML表单:

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @using (Html.BeginRouteForm("DefaultApi", new { httproute = "", controller = "images" }, FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <input type="file" name="image" multiple="multiple" accept="image/*" />
        <button type="submit">Upload</button>
    }
</body>  
</html>

更新2:

您似乎正在使用.NET 4.0。这是适用于.NET 4.0的ImagesController的修订版本:

public class ImagesController : ApiController
{
    public Task<HttpResponseMessage> Post()
    {
        if (!Request.Content.IsMimeMultipartContent("form-data"))
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        var uploadFolder = HostingEnvironment.MapPath("~/app_data");
        uploadFolder = Path.Combine(uploadFolder, DateTime.Now.ToString("yyyyMMddhhmmssfff"));
        Directory.CreateDirectory(uploadFolder);
        var streamProvider = new PreserveFilenameMultipartFileStreamProvider(uploadFolder);

        return Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
        {
            foreach (var uploadedFile in Directory.GetFiles(uploadFolder))
            {
                var thumbnail = Path.Combine(uploadFolder, "thumb-" + Path.GetFileName(uploadedFile));
                var medium = Path.Combine(uploadFolder, "medium-" + Path.GetFileName(uploadedFile));
                var large = Path.Combine(uploadFolder, "large-" + Path.GetFileName(uploadedFile));
                ImageTools.Resize(uploadedFile, thumbnail, 100, 100);
                ImageTools.Resize(uploadedFile, medium, 200, 200);
                ImageTools.Resize(uploadedFile, large, 300, 300);
            }
            return Request.CreateResponse(HttpStatusCode.Accepted);
        });
    }
}