J'ai créé une fonction permettant d'insérer des fichiers .png transparents téléchargés dans une base de données SQL Server et de les afficher sur une page Web via un HttpHandler.Comment préserver la transparence de png?
Bien que tout cela fonctionne, la transparence png devient noire lorsqu'elle est affichée sur la page Web. Y a-t-il un moyen de préserver la transparence?
Voilà mon service d'image qui insère dans la base de données du contrôleur MVC:
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);
}
Et voici la fonction d'aide « 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();
}
}
}
}
Que dois-je faire pour préserver la png transparence? S'il vous plaît montrer des exemples. Je ne suis pas vraiment un expert en manipulation d'image.
Merci.
Essayez d'utiliser 'Format32bppArgb' pour préserver l'alpha (c'est-à-dire 'A'). –
Veuillez ne pas préfixer vos titres de questions avec "C#" ou similaire. C'est ce que les tags sont pour. –
Savez-vous si votre .png d'origine est de 8 bits, ou est-ce en couleur? –