141 {
142 if (pixbuf == null)
143 throw new ArgumentNullException(nameof(pixbuf), "Pixbuf cannot be null.");
144
145
146 int width = pixbuf.Width;
147 int height = pixbuf.Height;
148 int rowstride = pixbuf.Rowstride;
149 bool hasAlpha = pixbuf.HasAlpha;
150 byte[] pixelData = pixbuf.PixelBytes.Data;
151
152
153 PixelFormat pixelFormat = hasAlpha ? PixelFormat.Format32bppArgb : PixelFormat.Format24bppRgb;
154 Bitmap bitmap = new Bitmap(width, height, pixelFormat);
155
156
157 BitmapData bmpData = bitmap.LockBits(
158 new Rectangle(0, 0, width, height),
159 ImageLockMode.WriteOnly,
160 pixelFormat);
161
162
163 IntPtr bmpPtr = bmpData.Scan0;
164 unsafe
165 {
166 byte* srcPtr = (byte*)pixbuf.Pixels;
167 byte* destPtr = (byte*)bmpPtr;
168
169 for (int y = 0; y < height; y++)
170 {
171 byte* srcRow = srcPtr + y * rowstride;
172 byte* destRow = destPtr + y * bmpData.Stride;
173
174 if (hasAlpha)
175 {
176 for (int x = 0; x < width; x++)
177 {
178 destRow[x * 4 + 0] = srcRow[x * 4 + 2];
179 destRow[x * 4 + 1] = srcRow[x * 4 + 1];
180 destRow[x * 4 + 2] = srcRow[x * 4 + 0];
181 destRow[x * 4 + 3] = srcRow[x * 4 + 3];
182 }
183 }
184 else
185 {
186 for (int x = 0; x < width; x++)
187 {
188 destRow[x * 3 + 0] = srcRow[x * 3 + 2];
189 destRow[x * 3 + 1] = srcRow[x * 3 + 1];
190 destRow[x * 3 + 2] = srcRow[x * 3 + 0];
191 }
192 }
193 }
194 }
195
196
197 bitmap.UnlockBits(bmpData);
198 return bitmap;
199 }