How to preserve png transparency? - c#

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))

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.

Generating Thumbnail C# from base64string

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;
}

Resize an image after upload and before saving it into the db

I have a simple web application (ASP.NET MVC 5 C#) which allows users to upload several files (images actually).
Currently it works well, the images are stored into the data base and I can read them later.
But I want to resize the images before saving them into the db, since the user can upload extremely big images.
Here is my controller:
public ActionResult Create(Annonce annonce, IEnumerable<HttpPostedFileBase> photos)
{
if (ModelState.IsValid)
{
// Read each uploaded files and add if into the collection
foreach (HttpPostedFileBase fichier in photos)
{
if (fichier != null && fichier.ContentLength > 0)
{
// Making a new object
var photo = new Photo
{
FileName = System.IO.Path.GetFileName(fichier.FileName),
ContentType = fichier.ContentType
};
using (var reader = new System.IO.BinaryReader(fichier.InputStream))
{
photo.Content = reader.ReadBytes(fichier.ContentLength);
}
// Add the current image to the collection
annonce.Photos.Add(photo);
}
}
db.Annonces.Add(annonce);
db.SaveChanges();
return RedirectToAction("Details", new { id = annonce.ID });
}
return View(annonce);
}
How can I resize my images and still be able to save them into the db?
Is-it even possible?
Thanks!
This code will perform a high quality resizing.(means you wont lose very much)
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;
}
Call ResizeImage() and assign it to a bitmap which you'll insert into your database.goodluck
you can convert it to byte array and than store it in your db as byte type
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
you can do the same but inverted to get it out and display it as image from the DB:
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
You also approach to ImageResizer as link below:
http://www.c-sharpcorner.com/article/image-resize-in-asp-net-mvc-using-image-resizer/

C#-Bitmap to Byte array

I have a method which saves the image from a panel. This method is using Bitmap class. I wants that my method should return byte array of the image.
private byte[] SaveImage()
{
byte[] byteContent = null;
using (Bitmap bitmap = new Bitmap(500, 500))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
Rectangle rectangle = myPanel.Bounds;
Point sourcePoints = myPanel.PointToScreen(new Point(myPanel.ClientRectangle.X, myPanel.ClientRectangle.Y));
g.CopyFromScreen(sourcePoints, Point.Empty, rectangle.Size);
}
string fileName = #"E:\\MyImages.Jpg";
bitmap.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
return byteContent;
}
You'll need to use a MemoryStream to serialize the bitmap to an image format and get the bytes;
using (Bitmap bitmap = new Bitmap(500, 500))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
...
}
using (var memoryStream = new MemoryStream())
{
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
return memoryStream.ToArray();
}
}
There are multiple output formats to choose from, you may instead want Bmp or MemoryBmp.

Image Resizing from SQL Database on the fly with MVC2

I have a simple MVC2 app that uploads a file from the browser to an MS SQL database as an Image blob.
Then I can return the results with something like:
public FileContentResult ShowPhoto(int id)
{
TemporaryImageUpload tempImageUpload = new TemporaryImageUpload();
tempImageUpload = _service.GetImageData(id) ?? null;
if (tempImageUpload != null)
{
byte[] byteArray = tempImageUpload.TempImageData;
return new FileContentResult (temp, "image/jpeg");
}
return null;
}
But I want to return these images resized as both thumbnails and as a gallery-sized view. Is this possible to do within this Result? I've been playing around with the great imageresizer.net but it seems to want to store the images on my server which I want to avoid. Is it possible to do this on the fly..?
I need to keep the original file and don't, if possible, want to store the images as files on the server.
Thanks for any pointers!
ImageResizer.NET allows you to pass a stream to it for resizing, see Managed API usage
The method you'd use is:
ImageResizer.ImageBuilder.Current.Build(object source, object dest, ResizeSettings settings)
I modified your method to go about it this way, but it is untested. Hope it helps.
public FileContentResult ShowPhoto(int id)
{
TemporaryImageUpload tempImageUpload = new TemporaryImageUpload();
tempImageUpload = _service.GetImageData(id) ?? null;
if (tempImageUpload != null)
{
byte[] byteArray = tempImageUpload.TempImageData;
using(var outStream = new MemoryStream()){
using(var inStream = new MemoryStream(byteArray)){
var settings = new ResizeSettings("maxwidth=200&maxheight=200");
ImageResizer.ImageBuilder.Current.Build(inStream, outStream, settings);
var outBytes = outStream.ToArray();
return new FileContentResult (outBytes, "image/jpeg");
}
}
}
return null;
}
There was a recent Hanselminutes podcast on Image Resizing with Nathanael Jones discussing some of the pitfalls of image resizing.
Even if you do not have 30 odd minutes to listen to the full podcast, the show notes point to some interesting resizing pitfalls, as well as an image resizing library also written by Nathanael Jones.
You could resize the image on the fly:
public void ResizeImage(Stream input, Stream output, int newWidth, int maxHeight)
{
using (var srcImage = Image.FromStream(input))
{
int newHeight = srcImage.Height * newWidth / srcImage.Width;
if (newHeight > maxHeight)
{
newWidth = srcImage.Width * maxHeight / srcImage.Height;
newHeight = maxHeight;
}
using (var newImage = new Bitmap(newWidth, newHeight))
using (var gr = Graphics.FromImage(newImage))
{
gr.SmoothingMode = SmoothingMode.AntiAlias;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
newImage.Save(output, ImageFormat.Jpeg);
}
}
}
and then you could have 2 controller actions (one that displays the full image size and one that displays a thumbnail):
public ActionResult Thumbnail(int id)
{
var tempImageUpload = new TemporaryImageUpload();
tempImageUpload = _service.GetImageData(id) ?? null;
if (tempImageUpload == null)
{
return HttpNotFound();
}
using (var input = new MemoryStream(tempImageUpload.TempImageData))
using (var output = new MemoryStream())
{
ResizeImage(input, output, 640, 1000);
return File(output.ToArray(), "image/jpeg");
}
}

Categories