ASP.NET MVC核心Azure Blob图像大小调整器

时间:2018-06-11 08:57:30

标签: azure asp.net-core asp.net-core-mvc azure-storage-blobs imageresizer

我有一个 ASP.NET核心应用程序,可将图像上传到 Azure 。在将所述图像上传到Azure Blob容器之前,我尝试使用 Magick.NET 调整图像大小。到目前为止,我已设法将图像保存到本地硬盘中的文件夹中。这是写这个的正确方法吗?

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Product products)
{
    var files = products.UploudThumbnail;

    List<string> image = new List<string>();
    List<string> names = new List<string>();

    if (files != null)
    {
        foreach (var file in files)
        {
            if (ModelState.IsValid)
            {
                if (file.ContentType == "image/jpeg" || file.ContentType == "image/jpg")
                {
                    if (file.Length < 1 * 1000 * 1000) 
                    {
                        var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);

                        var fileName = parsedContentDisposition.FileName.Trim('"');
                        names.Add(fileName);

                        fileName = Guid.NewGuid().ToString() + "-" + fileName;

                        CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);
                        cloudBlockBlob.Properties.ContentType = file.ContentType;
                        await cloudBlockBlob.UploadFromStreamAsync(file.OpenReadStream());

                        image.Add(cloudBlockBlob.Uri.AbsoluteUri);


                        const int size = 20;
                        const int quality = 75;

                        using (var image = new MagickImage(file.OpenReadStream()))
                        {
                            image.Resize(size, size);
                            image.Strip();
                            image.Quality = quality;
                            //how to save it into azure?
                            image.Write(fileName);
                        }

                    }
                    else
                    {
                        ModelState.AddModelError("UploudThumbnail", "Max size not accepted");
                    }
                }
                else
                {
                    ModelState.AddModelError("UploudThumbnail", "jpeg & jpg are accepted");
                }

            }
        }
    }

    _context.Add(products);
    await _context.SaveChangesAsync();
    return RedirectToAction(nameof(Index));
}

1 个答案:

答案 0 :(得分:0)

只需将图像写入内存流并使用UploadFromStreamAsync方法上传。

示例(伪):

/etc/redis/redis.conf
相关问题