Answer the question
In order to leave comments, you need to log in
How to make a checkerboard pattern for a transparent picture background in C#?
I am writing a thumbnail generator for graphic files (including transparent gif and png). The output is jpeg. If the source file had transparent areas, then black is displayed instead of them by default. It can be filled with a different color or pattern or texture. Everything is clear here:
public static Image Resize(this Image image,
int maxWidth, int maxHeight, bool notIncrease = true)
{
int w = image.Width;
int h = image.Height;
if (notIncrease && (w <= maxWidth && h <= maxHeight))
return (Image)image.Clone();
float ratioX = (float)maxWidth / (float)w;
float ratioY = (float)maxHeight / (float)h;
float ratio = Math.Min(ratioX, ratioY);
int newWidth = (int)(w * ratio);
int newHeight = (int)(h * ratio);
Image res = new Bitmap(newWidth, newHeight,
PixelFormat.Format24bppRgb);
using (var g = Graphics.FromImage(res))
{
g.FillRectangle(Brushes.Gray, 0, 0, newWidth, newHeight);
g.CompositingQuality =
CompositingQuality.HighQuality;
g.InterpolationMode =
InterpolationMode.HighQualityBicubic;
g.SmoothingMode =
SmoothingMode.HighQuality;
g.DrawImage(image, 0, 0,
newWidth, newHeight);
}
return res;
}
var bitmap = new Bitmap(20, 20);
using (var gg = Graphics.FromImage(bitmap))
{
gg.FillRectangle(Brushes.Gray, 0, 0, 10, 10);
gg.FillRectangle(Brushes.LightGray, 10, 0, 10, 10);
gg.FillRectangle(Brushes.LightGray, 0, 10, 10, 10);
gg.FillRectangle(Brushes.Gray, 10, 10, 10, 10);
}
var brush = new TextureBrush(bitmap);
var bitmap = new Bitmap(20, 20) = {
0x99,0x99,0x99, 0xcc,0xcc,0xcc,
0x99,0x99,0x99, 0xcc,0xcc,0xcc,
0x99,0x99,0x99, 0xcc,0xcc,0xcc,
0xcc,0xcc,0xcc, 0x99,0x99,0x99,
0xcc,0xcc,0xcc, 0x99,0x99,0x99,
0xcc,0xcc,0xcc, 0x99,0x99,0x99,
};
var brush = new TextureBrush(bitmap);
Answer the question
In order to leave comments, you need to log in
because we are talking about performance, then I would immediately prefer filling manually, without using brushes. so to speak, "to avoid misunderstandings." that is, 2 LockBits and a manual line-by-line copy (no need to BLIT or DrawImage) in a loop. well, yes, and the picture for filling over there is created for you above =) it’s quite static for itself)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question