简体   繁体   中英

How do I name multiple uploaded images and create directories for them in my ASP.NET Core Web Application?

My web application allows users to uploade multiple images for a product. The problem I have is that, I need to resize the uploaded images into specific widths and I also need to have them named accordingly. The below action shows you that, any uplaoded image is processed and gives the output location, but it can only process one image.

wwwroot/images/products/[some id]/image700.jpg
wwwroot/images/products/[some id]/image350.jpg
wwwroot/images/products/[some id]/image150.jpg

So, what if there is more than one image? I'm not sure how to handle that. Ideally I'd like something like:

wwwroot/images/products/[some id]/image01-700.jpg
wwwroot/images/products/[some id]/image01-350.jpg
wwwroot/images/products/[some id]/image01-150.jpg

wwwroot/images/products/[some id]/image02-700.jpg
wwwroot/images/products/[some id]/image02-350.jpg
wwwroot/images/products/[some id]/image02-150.jpg

wwwroot/images/products/[some id]/image03-700.jpg
wwwroot/images/products/[some id]/image03-350.jpg
wwwroot/images/products/[some id]/image03-150.jpg

Here is my controller

public Stream ProcessImages(Products model, int? id)
{
    /***************************
    *  These are the image sizes 
    *  I want to make from a single image
    ****************************/
    private readonly int[] sizeArray = new int[] { 700, 350, 150 };

    /***************************
    *  Start Process 
    ****************************/
    try
    {
        /***************************
        *  Define directories
        ****************************/  
        var images = model.ProductImages;
        var root = _env.WebRootPath;
        var folderName = Path.Combine(root, "images", "products", id.ToString());

        /***************************
        *  Create directory (none exists) 
        ****************************/
        if (!Directory.Exists(folderName))
        {
            Directory.CreateDirectory(folderName);
        }

        /***************************
        *  Iterate over the images
        ****************************/
        foreach (var item in images)
        {
            /***************************
            *  Iterate over the required
            *  sizes
            ****************************/
            foreach (var imageSize in sizeArray)
            {
                string imageSizeName = "image" + imageSize + ".jpg";
                string fullPath = Path.Combine(folderName, imageSizeName);
                
                //Create the stream and process the image
                using FileStream fileStream = new FileStream(fullPath, FileMode.Create, FileAccess.ReadWrite);

                try
                {
                    Stream inStream = item.OpenReadStream();
                    using Image image = Image.Load(inStream);
                    int width = imageSize;
                    int height = 0;
                    var clone = image.Clone(i => i.Resize(width, height));
                    clone.SaveAsJpeg(fileStream);
                    inStream.Position = 0;
                }
                catch (Exception ex)
                {
                     Console.WriteLine(ex.Message);
                 }
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    return (null);
}

Here is the model:

namespace MyProject.Data
{
    public class Products : BaseEntity
    {        
        public string Title { get; set; }        
        public IFormFileCollection ProductImages { get; set; }
        
    }
}

Does anyone know what I can do to process mulitple images in my situation?

for resizing the images you can use the following class

    public class ImageResizer
    {
        public void Image_resize(string input_Image_Path, string output_Image_Path, int new_Width)
        {
            const long quality = 50L;
            Bitmap source_Bitmap = new Bitmap(input_Image_Path);
            double dblWidth_origial = source_Bitmap.Width;
            double dblHeigth_origial = source_Bitmap.Height;
            double relation_heigth_width = dblHeigth_origial / dblWidth_origial;
            int new_Height = (int)(new_Width * relation_heigth_width);
            var new_DrawArea = new Bitmap(new_Width, new_Height);
            using (var graphic_of_DrawArea = Graphics.FromImage(new_DrawArea))
            {
                graphic_of_DrawArea.CompositingQuality = CompositingQuality.HighSpeed;
                graphic_of_DrawArea.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphic_of_DrawArea.CompositingMode = CompositingMode.SourceCopy;
                graphic_of_DrawArea.DrawImage(source_Bitmap, 0, 0, new_Width, new_Height);
                using (var output = System.IO.File.Open(output_Image_Path, FileMode.Create))
                {
                    var qualityParamId = System.Drawing.Imaging.Encoder.Quality;
                    var encoderParameters = new EncoderParameters(1);
                    encoderParameters.Param[0] = new EncoderParameter(qualityParamId, quality);
                    var codec = ImageCodecInfo.GetImageDecoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
                    new_DrawArea.Save(output, codec, encoderParameters);
                    output.Close();
                }
                graphic_of_DrawArea.Dispose();
            }
            source_Bitmap.Dispose();
        }
    }

the first argument defines where it can find the picture, the second one asks for a place to save the converted image and the last one asks you for picture width in pixles. ( exactly what you wanted )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM