简体   繁体   中英

How to create thumbnail image in .net core? Using the help of IFormFile

I need to create a thumbnail image from the original image and need to save both images in the local folder. I am using html file control for uploading the image

<input type="file" class="form-control" asp-for="ImageName" name="ProductImage" id="ProductImage">

And by the time of form submission I am getting it as IFromFile

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Guid id, ProductDTO product, IFormFile 
    ProductImage)
{
    if (ModelState.IsValid)
    {
        byte[] fileBytes;
        using (var ms = new MemoryStream())
        {
            ProductImage.CopyTo(ms);
            fileBytes = ms.ToArray();
        }
    }
}

I have converted it to byte[] and passing it to one of my method for saving it. Here I need the thumbnail of the particular image

What I have tried so far is to add the package Install-Package System.Drawing.Common -Version 4.5.1

And created a method for converting the image

public string ErrMessage;

public bool ThumbnailCallback()
{
    return false;
}
public Image GetReducedImage(int Width, int Height, Image ResourceImage)
{
    try
    {
        Image ReducedImage;

        Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);

        ReducedImage = ResourceImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);

        return ReducedImage;
    }
    catch (Exception e)
    {
        ErrMessage = e.Message;
        return null;
    }
}

But the method which I created is accepting a type of Image So little confused here, not sure how can we do that with byte[] . Also I am not getting the image local path from the IFileForm so i cannot directly give the path too.

Can someone help me to resolve this ?

Finally got the answer

Installed System.Drawing.Common -Version 4.5.1 package

Open the package manager and run the below code for installing the package

Install-Package System.Drawing.Common -Version 5.0.2

Then use the below code:

using System.Drawing;

var stream = ProductImage.OpenReadStream();

var newImage = GetReducedImage(32,32,stream);
newImage.Save("path+filename");

public Image GetReducedImage(int width, int height, Stream resourceImage)
{
    try
    {
        var image = Image.FromStream(resourceImage);
        var thumb = image.GetThumbnailImage(width, height, () => false, IntPtr.Zero);

        return thumb;
    }
    catch (Exception e)
    {
        return null;
    }
}

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