Hi
I'm uploading an image to a varbinary column in the database successfully. But I want to resize it before uploading.
So this is what I tried:
Guests model:
public byte[] Image { get; set; }
public string ContentType { get; set; } ImageExtentions Class to resize the image:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace System.Drawing
{
public static class ImageExtentions
{
public static Image Resize(this Image current, int maxWidth, int maxHeight)
{
int width, height;
if (current.Width > current.Height)
{
width = maxWidth;
height = Convert.ToInt32(current.Height * maxHeight / (double)current.Width);
}
else
{
width = Convert.ToInt32(current.Width * maxWidth / (double)current.Height);
height = maxHeight;
}
var canvas = new Bitmap(width, height);
using (var graphics = Graphics.FromImage(canvas))
{
graphics.CompositingQuality = CompositingQuality.HighSpeed;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.DrawImage(current, 0, 0, width, height);
}
return canvas;
}
public static byte[] ToByteArray(this Image current)
{
using (var stream = new MemoryStream())
{
current.Save(stream, current.RawFormat);
return stream.ToArray();
}
}
}
}
GuestsController:
//using a lot
using System.Drawing;
namespace Proj.Controllers
{
public class GuestsController : Controller
{
private readonly ApplicationDbContext _context; public GuestsController(ApplicationDbContext context) { _context = context; } //Some code [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Id,Name,DoB")] Guests guest, List<IFormFile> Image) { IFormFile uploadedImage = Image.FirstOrDefault(); if (ModelState.IsValid) { foreach (var item in Image) { if (item.Length > 0) { using (var stream = new MemoryStream()) { using (Image img = Image.FromStream(uploadedImage.OpenReadStream())) { Stream ms = new MemoryStream(img.Resize(900, 1000).ToByteArray()); FileStreamResult fsr = new FileStreamResult(ms, "image/jpg"); uploadedImage.OpenReadStream().CopyTo(stream); guest.Image = stream.ToArray(); guest.ContentType = uploadedImage.ContentType; } } } } } _context.Add(guest); await _context.SaveChangesAsync();
}
But this scenario gives me this error:
List<IFormFile> does not contain a definition for 'FromStream' and no accessible extension method 'FromStream' accepting a first argument of type List<IFormFile> could be found.
How to perform this task please?