In many places we are using custom size images like
for creating thumbnails, media applications etc..
In .net core it’s very easy to process the image
into new custom sized image.
Steps:
Install Nuget package System.Drawing.Common Version
4.5.1 into your project
Include a file control in the page with form enctype="multipart/form-data"
Exmple:
<form asp-action="ImageResizing" enctype="multipart/form-data">
<div class="form-group">
<div class="col-md-10">
<p>Upload one file using
this form:</p>
<input type="file" name="formFile" />
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input type="submit" value="Upload" />
</div>
</div>
</form>
Whenever we submit this form it will hit the
action ImageResizing.
.net core introduced a new interface IFormFile for sending file with
the HttpRequest.
We can get the actual file in our controller like
below
public async
Task<IActionResult> ImageResizing(IFormFile formFile)
{
//do your logic here
}
Then pass the file stream into our
ImageResizeMethod.
public async
Task<IActionResult> ImageResizing(IFormFile formFile)
{
if (formFile.Length > 0)
{
var filePath = Path.GetTempFileName();
using (var stream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
Image newFile= GetReducedImage (32,32 stream);
}
return View(nameof(Index));
}
private 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;
}
}
No comments:
Post a Comment