All pastes #37298 Raw Edit

Something

public text v1 · immutable
#37298 ·published 2006-01-18 21:49 UTC
rendered paste body
		internal static Image DIBtoImage(IntPtr dib_data) {
			BITMAPINFOHEADER	bmi;
			int			ncolors;
			int			imagesize;
			int			palettesize;
			Bitmap			bmp;
			BitmapData		bits;
			ColorPalette		pal;
			int[]			palette;
			byte[]			imagebits;

			bmi = (BITMAPINFOHEADER)Marshal.PtrToStructure(dib_data, typeof(BITMAPINFOHEADER));

			ncolors = (int)bmi.biClrUsed;
			if (ncolors == 0) {
				if (bmi.biBitCount < 24) {
					ncolors = (int)(1 << bmi.biBitCount);
				}
			}
			palettesize = ncolors * 4;

			imagesize = (int)bmi.biSizeImage;
			if (imagesize == 0) {
				imagesize = (int)(((((bmi.biWidth * bmi.biBitCount) + 31) & ~31) >> 3) * bmi.biHeight);
			}

			switch(bmi.biBitCount) {
				case 1: {	// Monochrome
					bmp = new Bitmap(bmi.biWidth, bmi.biHeight, PixelFormat.Format1bppIndexed);
					bits = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format1bppIndexed);
					palette = new int[2];
					break;
				}

				case 4: {	// 4bpp
					bmp = new Bitmap(bmi.biWidth, bmi.biHeight, PixelFormat.Format4bppIndexed);
					bits = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format4bppIndexed);
					palette = new int[16];
					break;
				}

				case 8: {	// 8bpp
					bmp = new Bitmap(bmi.biWidth, bmi.biHeight, PixelFormat.Format8bppIndexed);
					bits = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
					palette = new int[256];
					break;
				}

				case 24:
				case 32: {	// 32bpp
					bmp = new Bitmap(bmi.biWidth, bmi.biHeight, PixelFormat.Format32bppArgb);
					bits = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
					palette = new int[0];
					break;
				}

				default: {
					throw new Exception("Unexpected number of bits:" + bmi.biBitCount.ToString());
				}
			}

			if (bmi.biBitCount < 24) {
				pal = bmp.Palette;				// Managed palette
				Marshal.Copy((IntPtr)((int)dib_data + Marshal.SizeOf(typeof(BITMAPINFOHEADER))), palette, 0, palette.Length);

				for (int i = 0; i < ncolors; i++) {
					pal.Entries[i] = Color.FromArgb(palette[i]);
				}
			}

			imagebits = new byte[imagesize];

			// Copy from source to managed
			Marshal.Copy((IntPtr)((int)dib_data + Marshal.SizeOf(typeof(BITMAPINFOHEADER)) + palette.Length * 4), imagebits, 0, imagebits.Length);

			// Copy from managed to dest
			Marshal.Copy(imagebits, 0, bits.Scan0, imagebits.Length);

			bmp.UnlockBits(bits);

			return bmp;
		}