I created a function that allows you to load transparent .png files for insertion into a SQL Server database and displayed on a web page through HttpHandler.
While this all works, the png transparency changes to black when viewed on a web page. Is there a way to maintain transparency?
Here is my image service, which is inserted 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 is the helper function ResizeImageFile:
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 keep png transparent? Please show examples. I am seriously not a specialist in image processing.
Thanks.
source share