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 ?
To create thumbnail image with CSS, use the border property.
To create a thumbnail add an image using an HTML <img> tag. Also, Use CSS border property to add a border to the image. Set the smaller width to image with CSS width property.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With