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

Arunprasanth K V picture Arunprasanth K V · Jan 7, 2019 · Viewed 8.3k times · Source

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 ?

Answer

Arunprasanth K V picture Arunprasanth K V · Jan 7, 2019

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 4.5.1

Then use the below code

Stream stream=ProductImage.OpenReadStream();

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

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

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