I have a .NET Core 2.2 web app where I am storing user images in a SQL Server database. When I save the file as is, it displays in the web page with no problems.
After that I wanted to resize the image when the user uploads the file and installed Imagesharp package and used the following code to resize the image. The code runs perfectly but when the use logs in. the image is not displayed.
My code to resize and store the image into the database is:
Image Processing Methods
public Stream ResizeImage(Image<Rgba32> sourceImage, int destHeight, int destWidth)
{
sourceImage.Mutate<Rgba32>(ctx => ctx.Resize(destWidth,destHeight));
Stream outputStream = new MemoryStream();
sourceImage.Save(outputStream, new JpegEncoder());
return outputStream;
/*return sourceImage.
.Crop(new Rectangle(sourceX, sourceY, sourceWidth,
sourceHeight))
.Resize(destinationWidth, destinationHeight);*/
}
My code to store the image:
if (ModelState.IsValid)
{
if (ProfileImage != null)
{
var stream = ProfileImage.OpenReadStream();
Image<Rgba32> theimage = _imageProcessor.GetImageFromStream(stream);
var outstream = _imageProcessor.ResizeImage(theimage, 100, 100);
//Input.Image = commonData.ConvertToBytes(ProfileImage);
Input.Image = commonData.ConvertStreamToBytes(outstream);
}
var user = new ApplicationUser
{
UserName = Input.Email,
Email = Input.Email.ToLower().Trim(),
FirstName = Input.FirstName,
LastName = Input.LastName,
Image = Input.Image,
AccountDisabled = true
};
}
I am trying to display the image in html after converting it to the base64string as follows:
userView.UserImageBytes = new string(Convert.ToBase64String(userView.TheUser.Image));
My HTML markup to display the image:
<img src="data:image/jpg;base64,@Model.UserImageBytes" alt="No Image" />
The above code works fine but the stored image is not displayed.
How to display the image properly. Any help is appreciated.
After this line:
sourceImage.Save(outputStream, new JpegEncoder());
outputStream
is has its .Position set after the last written byte. You might, for instance, write more data to that stream after the image. In order for another bit of code to read the image, you need to reposition outputStream
before you return it. eg
outputStream.Position = 0;
return outputStream;