Generating Thumbnail C# from base64string - c#

I am trying to generate a thumbnail from the base64string. I am storing the image in a table and am trying to generate a thumbnail from the base64string being stored.
I am able to generate the thumbnail if I provide a path to the image, but that will not work in my case.
This is the working solution of generating a thumbnail from an image path:
protected void GenerateThumbnail(object sender, EventArgs e)
{
string path = Server.MapPath("../src/img/myImage.png");
System.Drawing.Image image = System.Drawing.Image.FromFile(path);
using (System.Drawing.Image thumbnail = image.GetThumbnailImage(100, 100, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero))
{
using (MemoryStream memoryStream = new MemoryStream())
{
thumbnail.Save(memoryStream, ImageFormat.Png);
Byte[] bytes = new Byte[memoryStream.Length];
memoryStream.Position = 0;
memoryStream.Read(bytes, 0, (int)bytes.Length);
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
Image2.ImageUrl = "data:image/png;base64," + base64String;
Image2.Visible = true;
}
}
}
Can anyone provide any advice on how to use the base64string instead of the image path the generate thumbnail?

Assuming, b64 is the base64 string, you can convert it to a byte array and use that to construct the starting image.
byte[] bytes = Convert.FromBase64String(b64);
using (MemoryStream ms = new MemoryStream(bytes))
{
Bitmap thumb = new Bitmap(100, 100);
using (Image bmp = Image.FromStream(ms))
{
using (Graphics g = Graphics.FromImage(thumb))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawImage(bmp, 0, 0, 100, 100);
}
}
// a picturebox to show/test the result
picOut.Image = thumb;
}
Be sure to dispose of the thumb when you are done with it.

Mixed few tricks found online. (one from #Plutonix)
string ThumbNailBase64 = ResizeBase64Image(YourBase64String,200, 300);
base64 Input => resize => base64 Output
You get the desired thumbnail with auto aspect ratio.
public static string ResizeBase64Image(string Base64String, int desiredWidth, int desiredHeight)
{
Base64String = Base64String.Replace("data:image/png;base64,", "");
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(Base64String);
using (MemoryStream ms = new MemoryStream(imageBytes))
{
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
var imag = ScaleImage(image, desiredWidth, desiredHeight);
using (MemoryStream ms1 = new MemoryStream())
{
//First Convert Image to byte[]
imag.Save(ms1, imag.RawFormat);
byte[] imageBytes1 = ms1.ToArray();
//Then Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes1);
return "data:image/png;base64,"+base64String;
}
}
}
public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var graphics = Graphics.FromImage(newImage))
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}

Related

How to convert JPEG to WebP format using .NET Core?

I have an ASP.NET Core 3.1 WebAPI that is responsible for providing other apps I have with images. I am trying to improve the performance of my apps. One of the feedback I get from running PageSpeed Insights test is to Serve images in next-gen formats.
All of the images that my WebAPI server are in JPEG format. I don't know much about image compression or image-formats, but I would like to evaluate the results from converting JPEG images to WebP as study show that WebP leads to better results.
I use the following ImageProcessor class to save uploaded images to my WebAPI.
public class ImageProcessor
{
public Image GetResizedImage(Stream stream, int newWidth, out ImageFormat imageFormat)
{
Image sourceImage = Image.FromStream(stream);
SizeF thumbSize = GetNewSize(sourceImage, newWidth);
imageFormat = sourceImage.RawFormat;
return ResizeImage(sourceImage, (int)thumbSize.Width, (int)thumbSize.Height);
}
protected SizeF GetNewSize(Image img, int newMaxWidth)
{
var size = new SizeF
{
Width = newMaxWidth,
Height = (newMaxWidth * img.Height) / img.Width
};
return size;
}
protected Bitmap ResizeImage(Image image, int width, int height)
{
var destRect = new Rectangle(0, 0, width, height);
var destImage = new Bitmap(width, height);
var xRes = Math.Max(Math.Min(image.HorizontalResolution, 96), 72);
var yRes = Math.Max(Math.Min(image.VerticalResolution, 96), 72);
destImage.SetResolution(xRes, yRes);
using (Graphics graphics = Graphics.FromImage(destImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (ImageAttributes wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
}
Here is how I call the ImageProcessor class to store images on disk from the controller
public async Task<IActionResult> Store(IFormFile file)
{
if(!ModelState.IsValid)
{
return Problem("Invalid model!");
}
// Process Image
Image image = GetResizedImage(file.OpenReadStream(), 1024, out ImageFormat imageFormat);
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, imageFormat);
memoryStream.Seek(0, SeekOrigin.Begin);
// Store it on disk
string fullPath = "full path to the new image";
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
using FileStream cacheWriter = new FileStream(fullPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write, 4096, true);
await memoryStream.CopyToAsync(cacheWriter);
return Ok();
}
Question
How can I store the image in a WebP format using .Net Core?
If I were you I would look at installing an instance of Thumbor or using Cloudinary to generate your webp files.
Then you can use JS to conditionally load the correct file.

GDI+ System.Runtime.InteropServices.ExternalException On Image resize and conversion

The ImageHandler class is responsible for converting the image to jpg and 60x60 size, then it converts it to Base64. The first Image is fine but when I try to proccess another image in the same run it crashes.
class ImageHandler
{
public static void convertToFormat(string filename)
{
var image = Image.FromFile(#filename);
var bitmap = ResizeImage(image, Globals.ImageSize, Globals.ImageSize);
bitmap.Save(Globals.PRED_PATH, ImageFormat.Jpeg);
}
public static Bitmap ResizeImage(Image image, int width, int height)
{
var destRect = new Rectangle(0, 0, width, height);
var destImage = new Bitmap(width, height);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(destImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
public static string ConvertImageToBase64String()
{
Image image = Image.FromFile(Globals.PRED_PATH);
var imageStream = new MemoryStream();
image.Save(imageStream, ImageFormat.Jpeg);
imageStream.Position = 0;
var imageBytes = imageStream.ToArray();
return Convert.ToBase64String(imageBytes);
}
}
Function Call:
ImageHandler.convertToFormat(FilePath);
string encodedImage = ImageHandler.ConvertImageToBase64String();
As a quick fix you can add image.Dispose(); after image.Save(imageStream, ImageFormat.Jpeg); in the method ConvertImageToBase64String to make it work.
However I would recommend that you add using statements to convertToFormat and ConvertImageToBase64String to properly free the resources after use.
public static void convertToFormat(string filename)
{
using (var image = Image.FromFile(#filename))
{
using (var bitmap = ResizeImage(image, Globals.ImageSize, Globals.ImageSize))
{
bitmap.Save(Globals.PRED_PATH, ImageFormat.Jpeg);
}
}
}
public static string ConvertImageToBase64String()
{
using (var image = Image.FromFile(Globals.PRED_PATH))
{
using (var imageStream = new MemoryStream())
{
image.Save(imageStream, ImageFormat.Jpeg);
imageStream.Position = 0;
var imageBytes = imageStream.ToArray();
return Convert.ToBase64String(imageBytes);
}
}
}

Resize Webp images

I had Converted Jpg to Webp But I want to resize the image.
using (Bitmap bitmap = new Bitmap(UploadName +jpgFileName))
{
using (var saveImageStream = System.IO.File.Open(webpFileName, FileMode.Create))
{
var encoder = new SimpleEncoder();
encoder.Encode(bitmap, saveImageStream, 90);
}
}
I think you can first resize in jpg then you convert from jpg to webp.
those methods i use to resize image:
You can recive a IFormFile jpgImage and convert to byte[] using method below:
public byte[] GetBytes(IFormFile formFile)
{
using var fileStream = formFile.OpenReadStream();
var bytes = new byte[formFile.Length];
fileStream.Read(bytes, 0, (int)formFile.Length);
return bytes;
}
// Methods to resize the jpg image in byte[]
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
...
public byte[] ResizeImage(byte[] img, int width, int height)
{
using var image = SixLabors.ImageSharp.Image.Load(img);
var options = new ResizeOptions
{
Size = new Size(width, height),
Mode = ResizeMode.Max
};
return Resize(image, options);
}
private byte[] Resize(Image<Rgba32> image, ResizeOptions resizeOptions)
{
byte[] ret;
image.Mutate(i => i.Resize(resizeOptions));
using MemoryStream ms = new MemoryStream();
image.SaveAsJpeg(ms);
ret = ms.ToArray();
ms.Close();
return ret;
}
After resize the jpg image in byte[] you convert to webp

A generic error occurred in GDI+.in html code save image path into the project

Haii..
Iam really struggling this error i tried all the links but iam not getting proper answer
first i want to do i save my byte image value into project file folder
i browse jpg image afer i asev into the project file path it throws the error
this is my code plase help me
string converted = data.OfUploadsName.Replace('-', '+');
converted = converted.Replace('_', '/');
string[] spilt=converted.Split(',');
byte[] bytes = Convert.FromBase64String(spilt[1]);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
//0.5
var newWidth = (int)(image.Width * 1);
var newHeight = (int)(image.Height * 1);
var thumbnailImg = new Bitmap(newWidth, newHeight);
var thumbGraph = Graphics.FromImage(thumbnailImg);
thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
thumbGraph.DrawImage(image, imageRectangle);
thumbnailImg.Save(HttpContext.Current.Server.MapPath(#"\SurveryDAL\Images\" + "'" + id + "'+.jpg"));

How to preserve png transparency?

I created a function to allow uploaded transparent .png files to be inserted into a SQL Server database and the displayed on a web page via an HttpHandler.
While this all works, the png transparency changes to black when it's viewed on the web page. Is there a way of preserving the transparency?
Here's my image service which inserts into the database from the MVC controller:
public void AddImage(int productId, string caption, byte[] bytesOriginal)
{
string jpgpattern = ".jpg|.JPG";
string pngpattern = ".png|.PNG";
string pattern = jpgpattern;
ImageFormat imgFormat = ImageFormat.Jpeg;
if (caption.ToLower().EndsWith(".png"))
{
imgFormat = ImageFormat.Png;
pattern = pngpattern;
}
ProductImage productImage = new ProductImage();
productImage.ProductId = productId;
productImage.BytesOriginal = bytesOriginal;
productImage.BytesFull = Helpers.ResizeImageFile(bytesOriginal, 600, imgFormat);
productImage.BytesPoster = Helpers.ResizeImageFile(bytesOriginal, 198, imgFormat);
productImage.BytesThumb = Helpers.ResizeImageFile(bytesOriginal, 100, imgFormat);
productImage.Caption = Common.RegexReplace(caption, pattern, "");
productImageDao.Insert(productImage);
}
And here's the "ResizeImageFile" helper function:
public static byte[] ResizeImageFile(byte[] imageFile, int targetSize, ImageFormat imageFormat)
{
using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile)))
{
Size newSize = CalculateDimensions(oldImage.Size, targetSize);
using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb))
{
using (Graphics canvas = Graphics.FromImage(newImage))
{
canvas.SmoothingMode = SmoothingMode.AntiAlias;
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
MemoryStream m = new MemoryStream();
newImage.Save(m, imageFormat);
return m.GetBuffer();
}
}
}
}
What do I need to do to preserve the png transparency? Please show examples. I'm seriously not an expert with image manipulation.
Thanks.
Maybe try changing pixel format form PixelFormat.Format24bppRgb to PixelFormat.Format32bppRgb. You need the extra 8 bits to hold the alpha channel.
Using PixelFormat.Format32bppRgb didn't work for me. What worked however is using oldImage.PixelFormat when drawing the new image. So the corresponding line of code becomes:
using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, oldImage.PixelFormat))

Categories