System.IntPtr.ToPointer()

Here are the examples of the csharp api System.IntPtr.ToPointer() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

778 Examples 7

19 Source : JobBars.Hooks.cs
with GNU Affero General Public License v3.0
from 0ceal0t

private void ReceiveActionEffect(int sourceId, IntPtr sourceCharacter, IntPtr pos, IntPtr effectHeader, IntPtr effectArray, IntPtr effectTrail) {
            if (!PlayerExists) {
                ReceiveActionEffectHook.Original(sourceId, sourceCharacter, pos, effectHeader, effectArray, effectTrail);
                return;
            }

            uint id = *((uint*)effectHeader.ToPointer() + 0x2);
            byte type = *((byte*)effectHeader.ToPointer() + 0x1F); // 1 = action

            var selfId = (int)ClientState.LocalPlayer.ObjectId;
            var isSelf = sourceId == selfId;
            var isPet = !isSelf && (GaugeManager?.CurrentJob == JobIds.SMN || GaugeManager?.CurrentJob == JobIds.SCH) && IsPet(sourceId, selfId);
            var isParty = !isSelf && !isPet && IsInParty((uint)sourceId);

            if (type != 1 || !(isSelf || isPet || isParty)) {
                ReceiveActionEffectHook.Original(sourceId, sourceCharacter, pos, effectHeader, effectArray, effectTrail);
                return;
            }

            var actionItem = new Item {
                Id = id,
                Type = (UIHelper.IsGCD(id) ? ItemType.GCD : ItemType.OGCD)
            };

            if (!isParty) { // don't let party members affect our gauge
                GaugeManager?.PerformAction(actionItem);
            }
            if (!isPet) {
                BuffManager?.PerformAction(actionItem, (uint)sourceId);
                CooldownManager?.PerformAction(actionItem, (uint)sourceId);
            }

            byte targetCount = *(byte*)(effectHeader + 0x21);

            int effectsEntries = 0;
            int targetEntries = 1;
            if (targetCount == 0) {
                effectsEntries = 0;
                targetEntries = 1;
            }
            else if (targetCount == 1) {
                effectsEntries = 8;
                targetEntries = 1;
            }
            else if (targetCount <= 8) {
                effectsEntries = 64;
                targetEntries = 8;
            }
            else if (targetCount <= 16) {
                effectsEntries = 128;
                targetEntries = 16;
            }
            else if (targetCount <= 24) {
                effectsEntries = 192;
                targetEntries = 24;
            }
            else if (targetCount <= 32) {
                effectsEntries = 256;
                targetEntries = 32;
            }

            List<EffectEntry> entries = new(effectsEntries);
            for (int i = 0; i < effectsEntries; i++) {
                entries.Add(*(EffectEntry*)(effectArray + i * 8));
            }

            ulong[] targets = new ulong[targetEntries];
            for (int i = 0; i < targetCount; i++) {
                targets[i] = *(ulong*)(effectTrail + i * 8);
            }

            for (int i = 0; i < entries.Count; i++) {
                ulong entryTarget = targets[i / 8];

                if (entries[i].type == ActionEffectType.ApplyStatusTarget || entries[i].type == ActionEffectType.ApplyStatusSource) {
                    var buffItem = new Item {
                        Id = entries[i].value,
                        Type = ItemType.Buff
                    };

                    if (!isParty) GaugeManager?.PerformAction(buffItem); // more accurate than using the status list
                }
            }

            ReceiveActionEffectHook.Original(sourceId, sourceCharacter, pos, effectHeader, effectArray, effectTrail);
        }

19 Source : KeyboardEvents.cs
with zlib License
from 0x0ade

public static bool GetKeyboardLayoutName(object pwszKLID) {
            // Let's just pretend EN - US (00000409)
            const string name = "00000409";

            if (pwszKLID is StringBuilder) {
                ((StringBuilder) pwszKLID).Append(name);
            } else if (pwszKLID is IntPtr) {
                // This is definitely wrong.
                unsafe
                {
                    char* str = (char*) ((IntPtr) pwszKLID).ToPointer();
                    for (int i = 0; i < name.Length; i++)
                        str[i] = name[i];
                }
            }

            return true; // No GetLastError
        }

19 Source : HeifByteArrayReader.cs
with GNU Lesser General Public License v3.0
from 0xC0000054

protected override bool ReadCore(IntPtr data, long count)
        {
            if (((ulong)this.position + (ulong)count) > (ulong)this.length)
            {
                return false;
            }

            unsafe
            {
                fixed (byte* source = this.buffer)
                {
                    Buffer.MemoryCopy(source + this.position, data.ToPointer(), count, count);
                }
            }
            this.position += count;

            return true;
        }

19 Source : BssomWriter.cs
with MIT License
from 1996v

internal unsafe void WriteBackArray3Header(long basePosition, IntPtr refOffset1, int count)
        {
            uint* refOffPtr1 = (uint*)refOffset1.ToPointer();
            long curPos = BufferWriter.Position;
            BufferWriter.SeekWithOutVerify(basePosition + 1, BssomSeekOrgin.Begin);
            ref byte refb = ref BufferWriter.GetRef((int)(*refOffPtr1) - 1);//lenPos
            //writeback len
            BssomBinaryPrimitives.WriteUInt32FixNumber(ref refb, checked((uint)(curPos - basePosition - BssomBinaryPrimitives.BuildInTypeCodeSize)));
            refb = ref Unsafe.Add(ref refb, BssomBinaryPrimitives.FixUInt32NumberSize);

            //write Field:count
            refb = ref Unsafe.Add(ref refb, BssomBinaryPrimitives.WriteVariableNumber(ref refb, (uint)count));

            for (int i = 0; i < count; i++)
            {
                BssomBinaryPrimitives.WriteUInt32FixNumber(ref refb, *(refOffPtr1 + i));
                refb = ref Unsafe.Add(ref refb, BssomBinaryPrimitives.FixUInt32NumberSize);
            }

            BufferWriter.SeekWithOutVerify(curPos, BssomSeekOrgin.Begin);
        }

19 Source : StackallocBlockProvider.cs
with MIT License
from 1996v

public static unsafe void WriteUInt(IntPtr ptr, int uintIndex, uint uintValue)
        {
            var uPtr = (uint*)ptr.ToPointer();
            *(uPtr + uintIndex) = uintValue;
        }

19 Source : ArgSet.cs
with MIT License
from Abc-Arbitrage

public void Format(StringBuffer stringBuffer, int index, StringView format)
        {
            var argPointer = (byte*)_argPointers[index + _argOffset].ToPointer();

            var dataPointer = argPointer;
            stringBuffer.Append(ref dataPointer, format, _strings, _argPointers, _totalArgCount);

            BytesRead += (int)(dataPointer - argPointer);
        }

19 Source : KeyValuePointerBuffer.cs
with MIT License
from Abc-Arbitrage

public unsafe byte* GetKeyPointer(int index)
            => (byte*)_keyPointers[index].ToPointer();

19 Source : LogEventTests.Append.cs
with MIT License
from Abc-Arbitrage

[SetUp]
        public void SetUp()
        {
            var buffer = new byte[_bufferLength];
            _bufferHandler = GCHandle.Alloc(buffer, GCHandleType.Pinned);

            var bufferSegment = new BufferSegment((byte*)_bufferHandler.AddrOfPinnedObject().ToPointer(), buffer.Length);
            _logEvent = new LogEvent(bufferSegment, _argCapacity);
            _logEvent.Initialize(Level.Info, null, LogEventArgumentExhaustionStrategy.Allocate);
            _output = new StringBuffer(128) { Culture = CultureInfo.InvariantCulture };
        }

19 Source : LogEventTests.EdgeCases.cs
with MIT License
from Abc-Arbitrage

[SetUp]
        public void SetUp()
        {
            var buffer = new byte[_bufferSize];
            _bufferHandler = GCHandle.Alloc(buffer, GCHandleType.Pinned);

            var bufferSegment = new BufferSegment((byte*)_bufferHandler.AddrOfPinnedObject().ToPointer(), buffer.Length);
            _logEvent = new LogEvent(bufferSegment, 10);
            _output = new StringBuffer(128) { Culture = CultureInfo.InvariantCulture };
        }

19 Source : ImageColorsConverter.cs
with GNU General Public License v3.0
from aiportal

public unsafe Image SaveImageWithNewColorTable(Image image)
		{
			Bitmap bitmap = null;
			Bitmap bitmap2 = null;
			Graphics graphics = null;
			BitmapData bitmapdata = null;
			BitmapData data2 = null;
			if (this._imgColors > 0x100)
			{
				this._imgColors = 0x100;
			}
			if (this._imgColors < 2)
			{
				this._imgColors = 2;
			}
			int width = image.Width;
			int height = image.Height;
			try
			{
				byte* numPtr;
				byte* numPtr2;
				bitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
				bitmap.Palette = this.pal;
				bitmap2 = new Bitmap(width, height, PixelFormat.Format32bppArgb);
				graphics = Graphics.FromImage(bitmap2);
				graphics.PageUnit = GraphicsUnit.Pixel;
				graphics.DrawImage(image, 0, 0, width, height);
				Rectangle rect = new Rectangle(0, 0, width, height);
				bitmapdata = bitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
				data2 = bitmap2.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
				IntPtr ptr = bitmapdata.Scan0;
				IntPtr ptr2 = data2.Scan0;
				if (bitmapdata.Stride > 0)
				{
					numPtr = (byte*)ptr.ToPointer();
				}
				else
				{
					numPtr = (byte*)ptr.ToPointer() + (bitmapdata.Stride * (height - 1));
				}
				if (data2.Stride > 0)
				{
					numPtr2 = (byte*)ptr2.ToPointer();
				}
				else
				{
					numPtr2 = (byte*)ptr2.ToPointer() + (data2.Stride * (height - 1));
				}
				uint num3 = (uint)Math.Abs(bitmapdata.Stride);
				uint num4 = (uint)Math.Abs(data2.Stride);
				for (uint i = 0; i < height; i++)
				{
					PixelData* dataPtr = (PixelData*)(numPtr2 + (i * num4));
					byte* numPtr3 = numPtr + (i * num3);
					for (uint j = 0; j < width; j++)
					{
						double num7 = ((dataPtr->red * 0.299) + (dataPtr->green * 0.587)) + (dataPtr->blue * 0.114);
						numPtr3[0] = (byte)(((num7 * (this._imgColors - 1)) / 255.0) + 0.5);
						dataPtr++;
						numPtr3++;
					}
				}
				bitmap.UnlockBits(bitmapdata);
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			finally
			{
				bitmap2.UnlockBits(data2);
				bitmap2.Dispose();
				graphics.Dispose();
				bitmapdata = null;
				data2 = null;
			}
			return bitmap;
		}

19 Source : ImageCompression.cs
with GNU General Public License v3.0
from aiportal

public static void SaveGrayScale(
			Image image,
			string filename,
			uint nColors,
			bool fTransparent
			)
		{

			// GIF codec supports 256 colors maximum, monochrome minimum.
			if (nColors > 256)
				nColors = 256;
			if (nColors < 2)
				nColors = 2;

			// Make a new 8-BPP indexed bitmap that is the same size as the source image.
			int Width = image.Width;
			int Height = image.Height;

			// Always use PixelFormat8bppIndexed because that is the color
			// table-based interface to the GIF codec.
			Bitmap bitmap = new Bitmap(Width,
									Height,
									PixelFormat.Format8bppIndexed);

			// Create a color palette big enough to hold the colors you want.
			ColorPalette pal = GetColorPalette(nColors);

			// Initialize a new color table with entries that are determined
			// by some optimal palette-finding algorithm; for demonstration 
			// purposes, use a grayscale.
			for (uint i = 0; i < nColors; i++)
			{
				uint Alpha = 0xFF;                      // Colors are opaque.
				uint Intensity = i * 0xFF / (nColors - 1);    // Even distribution. 

				// The GIF encoder makes the first entry in the palette
				// that has a ZERO alpha the transparent color in the GIF.
				// Pick the first one arbitrarily, for demonstration purposes.

				if (i == 0 && fTransparent) // Make this color index...
					Alpha = 0;          // Transparent

				// Create a gray scale for demonstration purposes.
				// Otherwise, use your favorite color reduction algorithm
				// and an optimum palette for that algorithm generated here.
				// For example, a color histogram, or a median cut palette.
				pal.Entries[i] = Color.FromArgb((int)Alpha,
												(int)Intensity,
												(int)Intensity,
												(int)Intensity);
			}

			// Set the palette into the new Bitmap object.
			bitmap.Palette = pal;


			// Use GetPixel below to pull out the color data of Image.
			// Because GetPixel isn't defined on an Image, make a copy 
			// in a Bitmap instead. Make a new Bitmap that is the same size as the
			// image that you want to export. Or, try to
			// interpret the native pixel format of the image by using a LockBits
			// call. Use PixelFormat32BppARGB so you can wrap a Graphics  
			// around it.
			Bitmap BmpCopy = new Bitmap(Width,
									Height,
									PixelFormat.Format32bppArgb);
			{
				Graphics g = Graphics.FromImage(BmpCopy);

				g.PageUnit = GraphicsUnit.Pixel;

				// Transfer the Image to the Bitmap
				g.DrawImage(image, 0, 0, Width, Height);

				// g goes out of scope and is marked for garbage collection.
				// Force it, just to keep things clean.
				g.Dispose();
			}

			// Lock a rectangular portion of the bitmap for writing.
			BitmapData bitmapData;
			Rectangle rect = new Rectangle(0, 0, Width, Height);

			bitmapData = bitmap.LockBits(
				rect,
				ImageLockMode.WriteOnly,
				PixelFormat.Format8bppIndexed);

			// Write to the temporary buffer that is provided by LockBits.
			// Copy the pixels from the source image in this loop.
			// Because you want an index, convert RGB to the appropriate
			// palette index here.
			IntPtr pixels = bitmapData.Scan0;

			unsafe
			{
				// Get the pointer to the image bits.
				// This is the unsafe operation.
				byte* pBits;
				if (bitmapData.Stride > 0)
					pBits = (byte*)pixels.ToPointer();
				else
					// If the Stide is negative, Scan0 points to the last 
					// scanline in the buffer. To normalize the loop, obtain
					// a pointer to the front of the buffer that is located 
					// (Height-1) scanlines previous.
					pBits = (byte*)pixels.ToPointer() + bitmapData.Stride * (Height - 1);
				uint stride = (uint)Math.Abs(bitmapData.Stride);

				for (uint row = 0; row < Height; ++row)
				{
					for (uint col = 0; col < Width; ++col)
					{
						// Map palette indexes for a gray scale.
						// If you use some other technique to color convert,
						// put your favorite color reduction algorithm here.
						Color pixel;    // The source pixel.

						// The destination pixel.
						// The pointer to the color index byte of the
						// destination; this real pointer causes this
						// code to be considered unsafe.
						byte* p8bppPixel = pBits + row * stride + col;

						pixel = BmpCopy.GetPixel((int)col, (int)row);

						// Use luminance/chrominance conversion to get grayscale.
						// Basically, turn the image into black and white TV.
						// Do not calculate Cr or Cb because you 
						// discard the color anyway.
						// Y = Red * 0.299 + Green * 0.587 + Blue * 0.114

						// This expression is best as integer math for performance,
						// however, because GetPixel listed earlier is the slowest 
						// part of this loop, the expression is left as 
						// floating point for clarity.

						double luminance = (pixel.R * 0.299) +
							(pixel.G * 0.587) +
							(pixel.B * 0.114);

						// Gray scale is an intensity map from black to white.
						// Compute the index to the grayscale entry that
						// approximates the luminance, and then round the index.
						// Also, constrain the index choices by the number of
						// colors to do, and then set that pixel's index to the 
						// byte value.
						*p8bppPixel = (byte)(luminance * (nColors - 1) / 255 + 0.5);

					} /* end loop for col */
				} /* end loop for row */
			} /* end unsafe */

			// To commit the changes, unlock the portion of the bitmap.  
			bitmap.UnlockBits(bitmapData);

			bitmap.Save(filename, ImageFormat.Png);

			// Bitmap goes out of scope here and is also marked for
			// garbage collection.
			// Pal is referenced by bitmap and goes away.
			// BmpCopy goes out of scope here and is marked for garbage
			// collection. Force it, because it is probably quite large.
			// The same applies to bitmap.
			BmpCopy.Dispose();
			bitmap.Dispose();
		}

19 Source : ImageCompressEngine.cs
with GNU General Public License v3.0
from aiportal

public static Image GrayScaleImage(Image srcImage)
		{
			try
			{
				int width = srcImage.Width;
				int height = srcImage.Height;
				Rectangle rect = new Rectangle(0, 0, width, height);

				Bitmap newBmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed) { Palette = GrayScalePalette };
				using (Bitmap srcBmp = new Bitmap(width, height, PixelFormat.Format32bppArgb))
				{
					using (Graphics g = Graphics.FromImage(srcBmp))
						g.DrawImage(srcImage, 0, 0);

					BitmapData srcData = srcBmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
					BitmapData newData = newBmp.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
					Debug.replacedert(srcData.Stride > 0);
					Debug.replacedert(newData.Stride > 0);
					int srcStride = srcData.Stride;
					int newStride = newData.Stride;
					unsafe
					{
						byte* pSrc = (byte*)srcData.Scan0.ToPointer();
						byte* pNew = (byte*)newData.Scan0.ToPointer();
						Argb* ps;
						byte* pn;
						for (int y = 0; y < height; ++y)
						{
							ps = (Argb*)(pSrc + (srcStride * y));
							pn = (byte*)(pNew + (newStride * y));
							for (int x = 0; x < width; ++x)
							{
								Argb color = *ps;
								*pn = (byte)((color.red * 0.299) + (color.green * 0.587) + (color.blue * 0.114) + 0.5);
								++ps;
								++pn;
							}
						}
					}
					srcBmp.UnlockBits(srcData);
					newBmp.UnlockBits(newData);
				}
				return newBmp;
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
		}

19 Source : ImageCompressEngine.cs
with GNU General Public License v3.0
from aiportal

public static Image TransparentColorImage(Image bgImage, Image srcImage, float ratio)
		{
			Debug.replacedert(srcImage != null && srcImage.PixelFormat == PixelFormat.Format16bppRgb555);
			Debug.replacedert(bgImage != null && bgImage.PixelFormat == PixelFormat.Format16bppRgb555);
			Debug.replacedert(srcImage.Width == bgImage.Width && srcImage.Height == bgImage.Height);
			Debug.replacedert(0 < ratio && ratio < 1);

			Image newImage = null;
			try
			{
				int width = bgImage.Width;
				int height = bgImage.Height;
				Rectangle rect = new Rectangle(0, 0, width, height);
				long diffMax = (int)(width * height * ratio);
				long diffCount = 0;

				Bitmap newBmp = new Bitmap(width, height, PixelFormat.Format16bppArgb1555);
				using (Bitmap srcBmp = new Bitmap(srcImage))
				using (Bitmap bgBmp = new Bitmap(bgImage))
				{
					BitmapData srcData = srcBmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format16bppRgb555);
					BitmapData bgData = bgBmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format16bppRgb555);
					BitmapData newData = newBmp.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format16bppArgb1555);
					Debug.replacedert(srcData.Stride == bgData.Stride && srcData.Stride == newData.Stride);
					int stride = srcData.Stride;
					unsafe
					{
						byte* pSrc = (byte*)srcData.Scan0.ToPointer();
						byte* pBkg = (byte*)bgData.Scan0.ToPointer();
						byte* pNew = (byte*)newData.Scan0.ToPointer();
						ushort* ps, pg, pn;
						for (int y = 0; y < height; ++y)
						{
							ps = (ushort*)(pSrc + (stride * y));
							pg = (ushort*)(pBkg+ (stride * y));
							pn = (ushort*)(pNew + (stride * y));
							for (int x = 0; x < width; ++x)
							{
								//if (0 == *ps)
								//    *pn = (ushort)(*ps | 0x8000);
								//else
									*pn = (ushort)((*pg == *ps) ? 0 : (*ps | 0x8000));
								++ps;
								++pg;
								++pn;

								diffCount += ((*pg == *ps) ? 0 : 1);
							}
							if (diffCount >= diffMax)
								break;
						}
					}
					srcBmp.UnlockBits(srcData);
					bgBmp.UnlockBits(bgData);
					newBmp.UnlockBits(newData);
				}

				if (diffCount < diffMax)
				{
					//newBmp.MakeTransparent(Color.Empty);
					newImage = newBmp;
				}
				else
				{
					newBmp.Dispose();
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return newImage;
		}

19 Source : ImageCompressEngine.cs
with GNU General Public License v3.0
from aiportal

public static byte[] XorGrayscaleImage(Image bgImage, Image srcImage, float ratio)
		{
			Debug.replacedert(srcImage != null && srcImage.PixelFormat == PixelFormat.Format8bppIndexed);
			Debug.replacedert(bgImage != null && bgImage.PixelFormat == PixelFormat.Format8bppIndexed);
			Debug.replacedert(srcImage.Width == bgImage.Width && srcImage.Height == bgImage.Height);
			Debug.replacedert(0 < ratio && ratio < 1);

			byte[] bsXor = null;
			try
			{
				int width = bgImage.Width;
				int height = bgImage.Height;
				Rectangle rect = new Rectangle(0, 0, width, height);
				long diffMax = (int)(width * height * ratio);
				long diffCount = 0;

				using (Bitmap srcBmp = new Bitmap(srcImage))
				using (Bitmap bkgBmp = new Bitmap(bgImage))
				using (Bitmap newBmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed))
				{
					BitmapData srcData = srcBmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
					BitmapData bkgData = bkgBmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
					BitmapData newData = newBmp.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
					Debug.replacedert(srcData.Stride == bkgData.Stride && srcData.Stride == newData.Stride);
					Debug.replacedert(srcData.Stride % 4 == 0);
					int stride = srcData.Stride;
					unsafe
					{
						byte* pSrc = (byte*)srcData.Scan0.ToPointer();
						byte* pBkg = (byte*)bkgData.Scan0.ToPointer();
						byte* pNew = (byte*)newData.Scan0.ToPointer();
						uint* ps, pg, pn;
						for (int y = 0; y < height; ++y)
						{
							ps = (uint*)(pSrc + (stride * y));
							pg = (uint*)(pBkg + (stride * y));
							pn = (uint*)(pNew + (stride * y));
							for (int x = 0; x < width; x += 4)
							{
								*pn = *pg ^ *ps;
								++ps;
								++pg;
								++pn;

								diffCount += ((*pg == *ps) ? 0 : 4);
							}
							if (diffCount >= diffMax)
								break;
						}
					}
					if (diffCount < diffMax)
					{
						bsXor = new byte[newData.Stride * newData.Height];
						Marshal.Copy(newData.Scan0, bsXor, 0, bsXor.Length);
					}
					srcBmp.UnlockBits(srcData);
					bkgBmp.UnlockBits(bkgData);
					newBmp.UnlockBits(newData);
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return bsXor;
		}

19 Source : ImageCompressEngine.cs
with GNU General Public License v3.0
from aiportal

public static Image CombineGrayscaleXor(Image srcImage, byte[] bsXor)
		{
			Debug.replacedert(srcImage != null && srcImage.PixelFormat == PixelFormat.Format8bppIndexed);
			Image newImage = null;
			try
			{
				int width = srcImage.Width;
				int height = srcImage.Height;
				Rectangle rect = new Rectangle(0, 0, width, height);

				Bitmap srcBmp = new Bitmap(srcImage);
				srcBmp.Palette = GrayScalePalette;
				BitmapData srcData = srcBmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
				Debug.replacedert(srcData.Stride * srcData.Height == bsXor.Length);
				Debug.replacedert(srcData.Stride % 4 == 0);
				int stride = srcData.Stride;
				unsafe
				{
					fixed (byte* pXor = bsXor)
					{
						byte* pSrc = (byte*)srcData.Scan0.ToPointer();
						uint* ps, px;
						for (int y = 0; y < height; ++y)
						{
							ps = (uint*)(pSrc + (stride * y));
							px = (uint*)(pXor + (stride * y));
							for (int x = 0; x < width; x += 4)
							{
								*ps = (*ps ^ *px);
								++ps;
								++px;
							}
						}
					}
				}
				srcBmp.UnlockBits(srcData);
				newImage = srcBmp;
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return newImage;
		}

19 Source : ImageCompressEngine.cs
with GNU General Public License v3.0
from aiportal

public static Image TransparentImage8(Image bgImage, Image srcImage, float ratio)
		{
			Debug.replacedert(srcImage != null && srcImage.PixelFormat == PixelFormat.Format8bppIndexed);
			Debug.replacedert(bgImage != null && bgImage.PixelFormat == PixelFormat.Format8bppIndexed);
			Debug.replacedert(srcImage.Width == bgImage.Width && srcImage.Height == bgImage.Height);
			Debug.replacedert(0 < ratio && ratio < 1);

			Image newImage = null;
			try
			{
				int width = bgImage.Width;
				int height = bgImage.Height;
				Rectangle rect = new Rectangle(0, 0, width, height);
				long diffMax = (int)(width * height * ratio);
				long diffCount = 0;

				Bitmap newBmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
				newBmp.Palette = srcImage.Palette;
				using (Bitmap srcBmp = new Bitmap(srcImage))
				using (Bitmap bkgBmp = new Bitmap(bgImage))
				{
					BitmapData srcData = srcBmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
					BitmapData bkgData = bkgBmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
					BitmapData newData = newBmp.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
					unsafe
					{
						byte* pSrc = (byte*)srcData.Scan0.ToPointer();
						byte* pBkg = (byte*)bkgData.Scan0.ToPointer();
						byte* pNew = (byte*)newData.Scan0.ToPointer();
						byte* ps, pg, pn;
						for (int y = 0; y < height; ++y)
						{
							ps = pSrc + (y * srcData.Stride);
							pg = pBkg + (y * bkgData.Stride);
							pn = pNew + (y * newData.Stride);
							for (int x = 0; x < width; ++x)
							{
								if (0 == *ps)
									*pn = 0xFF;
								else
									*pn = (byte)((*pg == *ps) ? 0 : *ps);
								++ps;
								++pg;
								++pn;

								diffCount += ((*pg == *ps) ? 0 : 1);
							}
							if (diffCount >= diffMax)
								break;
						}
					}
					srcBmp.UnlockBits(srcData);
					bkgBmp.UnlockBits(bkgData);
					newBmp.UnlockBits(newData);
				}

				if (diffCount < diffMax)
				{
					newBmp.MakeTransparent(Color.Empty);
					newImage = newBmp;
				}
				else
				{
					newBmp.Dispose();
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return newImage;
		}

19 Source : ImageCompressEngine.cs
with GNU General Public License v3.0
from aiportal

public static Image _TransparentImage8(Image bgImage, Image srcImage, float ratio, out bool transparent)
		{
			Debug.replacedert(srcImage != null && srcImage.PixelFormat == PixelFormat.Format8bppIndexed);
			Debug.replacedert(bgImage != null && bgImage.PixelFormat == PixelFormat.Format8bppIndexed);
			Debug.replacedert(srcImage.Width == bgImage.Width && srcImage.Height == bgImage.Height);
			Debug.replacedert(0 < ratio && ratio < 1);

			transparent = false;
			Image newImage = srcImage;
			try
			{
				int width = bgImage.Width;
				int height = bgImage.Height;
				Rectangle rect = new Rectangle(0, 0, width, height);
				long diffMax = (int)(width * height * ratio);
				long diffCount = 0;

				Bitmap newBmp = new Bitmap(srcImage);
				using (Bitmap bgBmp = new Bitmap(bgImage))
				{
					BitmapData bgData = bgBmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
					BitmapData newData = newBmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
					unsafe
					{
						byte* pBkg = (byte*)bgData.Scan0.ToPointer();
						byte* pNew = (byte*)newData.Scan0.ToPointer();
						byte* pg = pBkg;
						byte* pn = pNew;
						for (int y = 0; y < height; ++y)
						{
							pg = pBkg + (y * bgData.Stride);
							pn = pNew + (y * newData.Stride);
							for (int x = 0; x < width; ++x)
							{
								diffCount += ((*pg == *pn) ? 0 : 1);
								if (0 == *pn)
									*pn = 1;
								else
									*pn = (byte)((*pg == *pn) ? 0 : *pn);
								++pg;
								++pn;
							}
							if (diffCount >= diffMax)
								break;
						}
					}
					newBmp.UnlockBits(newData);
					bgBmp.UnlockBits(bgData);
				}

				if (diffCount < diffMax)
				{
					newBmp.MakeTransparent(Color.Empty);
					newImage = newBmp;
					transparent = true;
				}
				else
				{
					newBmp.Dispose();
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return newImage;
		}

19 Source : ImageCompression.cs
with GNU General Public License v3.0
from aiportal

public static Image GrayScale(Image image)
		{
			// Make a new 8-BPP indexed bitmap that is the same size as the source image.
			int Width = image.Width;
			int Height = image.Height;
			int nColors = 256;
			Bitmap bitmap = new Bitmap(Width, Height, PixelFormat.Format8bppIndexed);

			// fill palette
			ColorPalette pal = bitmap.Palette;
			for (int i = 0; i < nColors; i++)
			{
				int Alpha = (i == 0) ? 0x00 : 0xFF;
				int Intensity = i * 0xFF / (nColors - 1);
				pal.Entries[i] = Color.FromArgb(Alpha, Intensity, Intensity, Intensity);
			}

			Rectangle rect = new Rectangle(0, 0, Width, Height);

			BitmapData bitmapData = bitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);

			// Write to the temporary buffer that is provided by LockBits.
			// Copy the pixels from the source image in this loop.
			// Because you want an index, convert RGB to the appropriate
			// palette index here.
			IntPtr pixels = bitmapData.Scan0;

			unsafe
			{
				// Get the pointer to the image bits.
				// This is the unsafe operation.
				byte* pBits;
				if (bitmapData.Stride > 0)
					pBits = (byte*)pixels.ToPointer();
				else
					// If the Stide is negative, Scan0 points to the last 
					// scanline in the buffer. To normalize the loop, obtain
					// a pointer to the front of the buffer that is located 
					// (Height-1) scanlines previous.
					pBits = (byte*)pixels.ToPointer() + bitmapData.Stride * (Height - 1);
				uint stride = (uint)Math.Abs(bitmapData.Stride);

				for (uint row = 0; row < Height; ++row)
				{
					for (uint col = 0; col < Width; ++col)
					{
						//Color pixel;    // The source pixel.

						// The destination pixel.
						// The pointer to the color index byte of the
						// destination; this real pointer causes this
						// code to be considered unsafe.
						byte* p8bppPixel = pBits + row * stride + col;

						//pixel = image.GetPixel((int)col, (int)row);

						// Use luminance/chrominance conversion to get grayscale.
						// Basically, turn the image into black and white TV.
						// Do not calculate Cr or Cb because you 
						// discard the color anyway.
						// Y = Red * 0.299 + Green * 0.587 + Blue * 0.114

						// This expression is best as integer math for performance,
						// however, because GetPixel listed earlier is the slowest 
						// part of this loop, the expression is left as 
						// floating point for clarity.

						//double luminance = (pixel.R * 0.299) +
						//    (pixel.G * 0.587) +
						//    (pixel.B * 0.114);

						// Gray scale is an intensity map from black to white.
						// Compute the index to the grayscale entry that
						// approximates the luminance, and then round the index.
						// Also, constrain the index choices by the number of
						// colors to do, and then set that pixel's index to the 
						// byte value.
						//*p8bppPixel = (byte)(luminance * (nColors - 1) / 255 + 0.5);

					} /* end loop for col */
				} /* end loop for row */
			} /* end unsafe */

			// To commit the changes, unlock the portion of the bitmap.  
			bitmap.UnlockBits(bitmapData);

			// Bitmap goes out of scope here and is also marked for
			// garbage collection.
			// Pal is referenced by bitmap and goes away.
			// BmpCopy goes out of scope here and is marked for garbage
			// collection. Force it, because it is probably quite large.
			// The same applies to bitmap.
			bitmap.Dispose();
			return null;
		}

19 Source : ImageCompression.cs
with GNU General Public License v3.0
from aiportal

public static void SaveGrayScale(Image image, string filename, uint nColors, bool fTransparent)
		{

			// GIF codec supports 256 colors maximum, monochrome minimum.
			if (nColors > 256)
				nColors = 256;
			if (nColors < 2)
				nColors = 2;

			// Make a new 8-BPP indexed bitmap that is the same size as the source image.
			int Width = image.Width;
			int Height = image.Height;

			// Always use PixelFormat8bppIndexed because that is the color
			// table-based interface to the GIF codec.
			Bitmap bitmap = new Bitmap(Width,
									Height,
									PixelFormat.Format8bppIndexed);

			// Create a color palette big enough to hold the colors you want.
			ColorPalette pal = GetColorPalette(nColors);

			// Initialize a new color table with entries that are determined
			// by some optimal palette-finding algorithm; for demonstration 
			// purposes, use a grayscale.
			for (uint i = 0; i < nColors; i++)
			{
				uint Alpha = 0xFF;                      // Colors are opaque.
				uint Intensity = i * 0xFF / (nColors - 1);    // Even distribution. 

				// The GIF encoder makes the first entry in the palette
				// that has a ZERO alpha the transparent color in the GIF.
				// Pick the first one arbitrarily, for demonstration purposes.

				if (i == 0 && fTransparent) // Make this color index...
					Alpha = 0;          // Transparent

				// Create a gray scale for demonstration purposes.
				// Otherwise, use your favorite color reduction algorithm
				// and an optimum palette for that algorithm generated here.
				// For example, a color histogram, or a median cut palette.
				pal.Entries[i] = Color.FromArgb((int)Alpha,
												(int)Intensity,
												(int)Intensity,
												(int)Intensity);
			}

			// Set the palette into the new Bitmap object.
			bitmap.Palette = pal;


			// Use GetPixel below to pull out the color data of Image.
			// Because GetPixel isn't defined on an Image, make a copy 
			// in a Bitmap instead. Make a new Bitmap that is the same size as the
			// image that you want to export. Or, try to
			// interpret the native pixel format of the image by using a LockBits
			// call. Use PixelFormat32BppARGB so you can wrap a Graphics  
			// around it.
			Bitmap BmpCopy = new Bitmap(Width,
									Height,
									PixelFormat.Format32bppArgb);
			{
				Graphics g = Graphics.FromImage(BmpCopy);

				g.PageUnit = GraphicsUnit.Pixel;

				// Transfer the Image to the Bitmap
				g.DrawImage(image, 0, 0, Width, Height);

				// g goes out of scope and is marked for garbage collection.
				// Force it, just to keep things clean.
				g.Dispose();
			}

			// Lock a rectangular portion of the bitmap for writing.
			BitmapData bitmapData;
			Rectangle rect = new Rectangle(0, 0, Width, Height);

			bitmapData = bitmap.LockBits(
				rect,
				ImageLockMode.WriteOnly,
				PixelFormat.Format8bppIndexed);

			// Write to the temporary buffer that is provided by LockBits.
			// Copy the pixels from the source image in this loop.
			// Because you want an index, convert RGB to the appropriate
			// palette index here.
			IntPtr pixels = bitmapData.Scan0;

			unsafe
			{
				// Get the pointer to the image bits.
				// This is the unsafe operation.
				byte* pBits;
				if (bitmapData.Stride > 0)
					pBits = (byte*)pixels.ToPointer();
				else
					// If the Stide is negative, Scan0 points to the last 
					// scanline in the buffer. To normalize the loop, obtain
					// a pointer to the front of the buffer that is located 
					// (Height-1) scanlines previous.
					pBits = (byte*)pixels.ToPointer() + bitmapData.Stride * (Height - 1);
				uint stride = (uint)Math.Abs(bitmapData.Stride);

				for (uint row = 0; row < Height; ++row)
				{
					for (uint col = 0; col < Width; ++col)
					{
						// Map palette indexes for a gray scale.
						// If you use some other technique to color convert,
						// put your favorite color reduction algorithm here.
						Color pixel;    // The source pixel.

						// The destination pixel.
						// The pointer to the color index byte of the
						// destination; this real pointer causes this
						// code to be considered unsafe.
						byte* p8bppPixel = pBits + row * stride + col;

						pixel = BmpCopy.GetPixel((int)col, (int)row);

						// Use luminance/chrominance conversion to get grayscale.
						// Basically, turn the image into black and white TV.
						// Do not calculate Cr or Cb because you 
						// discard the color anyway.
						// Y = Red * 0.299 + Green * 0.587 + Blue * 0.114

						// This expression is best as integer math for performance,
						// however, because GetPixel listed earlier is the slowest 
						// part of this loop, the expression is left as 
						// floating point for clarity.

						double luminance = (pixel.R * 0.299) +
							(pixel.G * 0.587) +
							(pixel.B * 0.114);

						// Gray scale is an intensity map from black to white.
						// Compute the index to the grayscale entry that
						// approximates the luminance, and then round the index.
						// Also, constrain the index choices by the number of
						// colors to do, and then set that pixel's index to the 
						// byte value.
						*p8bppPixel = (byte)(luminance * (nColors - 1) / 255 + 0.5);

					} /* end loop for col */
				} /* end loop for row */
			} /* end unsafe */

			// To commit the changes, unlock the portion of the bitmap.  
			bitmap.UnlockBits(bitmapData);

			bitmap.Save(filename, ImageFormat.Png);

			// Bitmap goes out of scope here and is also marked for
			// garbage collection.
			// Pal is referenced by bitmap and goes away.
			// BmpCopy goes out of scope here and is marked for garbage
			// collection. Force it, because it is probably quite large.
			// The same applies to bitmap.
			BmpCopy.Dispose();
			bitmap.Dispose();
		}

19 Source : ImageCompression.cs
with GNU General Public License v3.0
from aiportal

public static Image GrayScaleCompress(Image image)
		{
			uint nColors = 256;
			bool fTransparent = true;

			// Make a new 8-BPP indexed bitmap that is the same size as the source image.
			int Width = image.Width;
			int Height = image.Height;

			// Always use PixelFormat8bppIndexed because that is the color
			// table-based interface to the GIF codec.
			Bitmap bitmap = new Bitmap(Width,
									Height,
									PixelFormat.Format8bppIndexed);

			// Create a color palette big enough to hold the colors you want.
			ColorPalette pal = GetColorPalette(nColors);

			// Initialize a new color table with entries that are determined
			// by some optimal palette-finding algorithm; for demonstration 
			// purposes, use a grayscale.
			for (uint i = 0; i < nColors; i++)
			{
				uint Alpha = 0xFF;                      // Colors are opaque.
				uint Intensity = i * 0xFF / (nColors - 1);    // Even distribution. 

				// The GIF encoder makes the first entry in the palette
				// that has a ZERO alpha the transparent color in the GIF.
				// Pick the first one arbitrarily, for demonstration purposes.

				if (i == 0 && fTransparent) // Make this color index...
					Alpha = 0;          // Transparent

				// Create a gray scale for demonstration purposes.
				// Otherwise, use your favorite color reduction algorithm
				// and an optimum palette for that algorithm generated here.
				// For example, a color histogram, or a median cut palette.
				pal.Entries[i] = Color.FromArgb((int)Alpha,
												(int)Intensity,
												(int)Intensity,
												(int)Intensity);
			}

			// Set the palette into the new Bitmap object.
			bitmap.Palette = pal;


			// Use GetPixel below to pull out the color data of Image.
			// Because GetPixel isn't defined on an Image, make a copy 
			// in a Bitmap instead. Make a new Bitmap that is the same size as the
			// image that you want to export. Or, try to
			// interpret the native pixel format of the image by using a LockBits
			// call. Use PixelFormat32BppARGB so you can wrap a Graphics  
			// around it.
			Bitmap BmpCopy = new Bitmap(Width,
									Height,
									PixelFormat.Format32bppArgb);
			{
				Graphics g = Graphics.FromImage(BmpCopy);

				g.PageUnit = GraphicsUnit.Pixel;

				// Transfer the Image to the Bitmap
				g.DrawImage(image, 0, 0, Width, Height);

				// g goes out of scope and is marked for garbage collection.
				// Force it, just to keep things clean.
				g.Dispose();
			}

			// Lock a rectangular portion of the bitmap for writing.
			BitmapData bitmapData;
			Rectangle rect = new Rectangle(0, 0, Width, Height);

			bitmapData = bitmap.LockBits(
				rect,
				ImageLockMode.WriteOnly,
				PixelFormat.Format8bppIndexed);

			// Write to the temporary buffer that is provided by LockBits.
			// Copy the pixels from the source image in this loop.
			// Because you want an index, convert RGB to the appropriate
			// palette index here.
			IntPtr pixels = bitmapData.Scan0;

			unsafe
			{
				// Get the pointer to the image bits.
				// This is the unsafe operation.
				byte* pBits;
				if (bitmapData.Stride > 0)
					pBits = (byte*)pixels.ToPointer();
				else
					// If the Stide is negative, Scan0 points to the last 
					// scanline in the buffer. To normalize the loop, obtain
					// a pointer to the front of the buffer that is located 
					// (Height-1) scanlines previous.
					pBits = (byte*)pixels.ToPointer() + bitmapData.Stride * (Height - 1);
				uint stride = (uint)Math.Abs(bitmapData.Stride);

				for (uint row = 0; row < Height; ++row)
				{
					for (uint col = 0; col < Width; ++col)
					{
						// Map palette indexes for a gray scale.
						// If you use some other technique to color convert,
						// put your favorite color reduction algorithm here.
						Color pixel;    // The source pixel.

						// The destination pixel.
						// The pointer to the color index byte of the
						// destination; this real pointer causes this
						// code to be considered unsafe.
						byte* p8bppPixel = pBits + row * stride + col;

						pixel = BmpCopy.GetPixel((int)col, (int)row);

						// Use luminance/chrominance conversion to get grayscale.
						// Basically, turn the image into black and white TV.
						// Do not calculate Cr or Cb because you 
						// discard the color anyway.
						// Y = Red * 0.299 + Green * 0.587 + Blue * 0.114

						// This expression is best as integer math for performance,
						// however, because GetPixel listed earlier is the slowest 
						// part of this loop, the expression is left as 
						// floating point for clarity.

						double luminance = (pixel.R * 0.299) +
							(pixel.G * 0.587) +
							(pixel.B * 0.114);

						// Gray scale is an intensity map from black to white.
						// Compute the index to the grayscale entry that
						// approximates the luminance, and then round the index.
						// Also, constrain the index choices by the number of
						// colors to do, and then set that pixel's index to the 
						// byte value.
						*p8bppPixel = (byte)(luminance * (nColors - 1) / 255 + 0.5);

					} /* end loop for col */
				} /* end loop for row */
			} /* end unsafe */

			// To commit the changes, unlock the portion of the bitmap.  
			bitmap.UnlockBits(bitmapData);

			// Bitmap goes out of scope here and is also marked for
			// garbage collection.
			// Pal is referenced by bitmap and goes away.
			// BmpCopy goes out of scope here and is marked for garbage
			// collection. Force it, because it is probably quite large.
			// The same applies to bitmap.
			BmpCopy.Dispose();
			//bitmap.Dispose();
			return bitmap;
		}

19 Source : ImageCompressEngine.cs
with GNU General Public License v3.0
from aiportal

public static Bitmap IndexedColorBitmap(Image img)
		{
			Bitmap newImage = null;
			try
			{
				int width = img.Width;
				int height = img.Height;
				Rectangle rect = new Rectangle(0, 0, width, height);

				Bitmap newBitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
				newBitmap.Palette = ColorIndexedPalette;
				using (Bitmap srcBitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb))
				{
					using (Graphics g = Graphics.FromImage(srcBitmap))
					{
						g.PageUnit = GraphicsUnit.Pixel;
						g.DrawImage(img, 0, 0);
					}
					var srcData = srcBitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
					var newData = newBitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
					unsafe
					{
						int srcStride = Math.Abs(srcData.Stride);
						int newStride = Math.Abs(newData.Stride);
						byte* pSrc = (byte*)srcData.Scan0.ToPointer() + (srcData.Stride > 0 ? 0 : (srcData.Stride * (height - 1)));
						byte* pNew = (byte*)newData.Scan0.ToPointer() + (newData.Stride > 0 ? 0 : (newData.Stride * (height - 1)));
						PixelData* ps;
						byte* pn;
						for (uint y = 0; y < height; y++)
						{
							ps = (PixelData*)(pSrc + (srcStride * y));
							pn = pNew + (newStride * y);
							for (uint x = 0; x < width; x++)
							{
								//*pn = (byte)(((ps->red >> 6) << 4) | ((ps->green >> 6) << 2) | (ps->blue >> 6));
								byte r = (byte)(ps->red * 3 / 255.0);
								byte g = (byte)(ps->green * 3 / 255.0);
								byte b = (byte)(ps->blue * 3 / 255.0);
								Debug.replacedert(r < 4 && g < 4 && b < 4);
								*pn = (byte)(r << 4 | g << 2 | b);

								++ps;
								++pn;
							}
						}
					}
					srcBitmap.UnlockBits(srcData);
					newBitmap.UnlockBits(newData);
					srcData = null;
					newData = null;
				}
				newImage = newBitmap;
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return newImage;
		}

19 Source : ImageCompressEngine.cs
with GNU General Public License v3.0
from aiportal

public static Bitmap GrayScaleBitmap(Image img)
		{
			Bitmap newImage = null;
			try
			{
				int nColors = 8;
				int width = img.Width;
				int height = img.Height;
				Rectangle rect = new Rectangle(0, 0, width, height);

				Bitmap newBitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
				newBitmap.Palette = GrayScalePalette;
				using (Bitmap srcBitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb))
				{
					using (Graphics g = Graphics.FromImage(srcBitmap))
					{
						g.PageUnit = GraphicsUnit.Pixel;
						g.DrawImage(img, 0, 0);
					}
					var srcData = srcBitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
					var newData = newBitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
					unsafe
					{
						int srcStride = Math.Abs(srcData.Stride);
						int newStride = Math.Abs(newData.Stride);
						byte* pSrc = (byte*)srcData.Scan0.ToPointer() + ((srcData.Stride > 0) ? 0 : (srcData.Stride * (height - 1)));
						byte* pNew = newData.Stride > 0 ? (byte*)newData.Scan0.ToPointer() : (byte*)newData.Scan0.ToPointer() + (newData.Stride * (height - 1));
						PixelData* ps;
						byte* pn;
						for (uint y = 0; y < height; y++)
						{
							ps = (PixelData*)(pSrc + (srcStride * y));
							pn = pNew + (newStride * y);
							for (uint x = 0; x < width; x++)
							{
								double dv = ((ps->red * 0.299) + (ps->green * 0.587)) + (ps->blue * 0.114);
								pn[0] = (byte)(((dv * (nColors - 1)) / 255.0) + 0.5);

								++ps;
								++pn;
							}
						}
					}
					srcBitmap.UnlockBits(srcData);
					newBitmap.UnlockBits(newData);
					srcData = null;
					newData = null;
				}
				newImage = newBitmap;
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return newImage;
		}

19 Source : AudioKernelExtensions.cs
with MIT License
from aksyr

private static void ExecuteKernel(ref TAudioKernel kernel, IntPtr audioDataPtr)
            {
                var audioData = (NativeAudioData*)audioDataPtr.ToPointer();
                var context = new ExecuteContext<TParameters, TProviders>
                {
                    DSPClock = (long)audioData->DSPClock,
                    DSPBufferSize = (int)audioData->DSPBufferSize,
                    SampleRate = (int)audioData->SampleRate,
                    GraphBuffer = (DSPGraph*)audioData->GraphRegistry,
                    GraphIndex = audioData->GraphIndex,
                    NodeIndex = audioData->NodeIndex,
                    Inputs = new SampleBufferArray
                    {
                        Count = (int)audioData->InputBufferCount,
                        Buffers = audioData->InputBuffers,
                        SampleCount = (int)audioData->SampleReadCount,
#if ENABLE_UNITY_COLLECTIONS_CHECKS
                        Safety = audioData->ReadOnlySafetyHandle
#endif
                    },
                    Outputs = new SampleBufferArray
                    {
                        Count = (int)audioData->OutputBufferCount,
                        Buffers = audioData->OutputBuffers,
                        SampleCount = (int)audioData->SampleReadCount,
#if ENABLE_UNITY_COLLECTIONS_CHECKS
                        Safety = audioData->ReadWriteSafetyHandle
#endif
                    },
                    Parameters = new ParameterData<TParameters>
                    {
                        Parameters = audioData->Parameters,
                        ParametersCount = (int)audioData->ParameterCount,
                        ReadLength = (int)audioData->SampleReadCount,
                        ParameterKeys = audioData->ParameterKeys,
                        DSPClock = (long)audioData->DSPClock,
                    },
                    Providers = new SampleProviderContainer<TProviders>
                    {
                        Count = (int)audioData->SampleProviderIndexCount,
                        SampleProviderIndices = audioData->SampleProviderIndices,
                        SampleProvidersCount = (int)audioData->SampleProviderCount,
                        SampleProviders = audioData->SampleProviders,
#if ENABLE_UNITY_COLLECTIONS_CHECKS
                        Safety = audioData->ReadOnlySafetyHandle
#endif
                    }
                };

                kernel.Execute(ref context);

                // Set final parameter values for readback to native
                for (int i = 0; i < context.Parameters.ParametersCount; ++i)
                    context.Parameters.Parameters[i].m_Value = context.Parameters.GetFloat(i, context.DSPBufferSize - 1);
            }

19 Source : AudioOutputExtensions.cs
with MIT License
from aksyr

public static unsafe void Execute(ref TOutput data, IntPtr userData, IntPtr method, ref JobRanges ranges, int jobIndex)
            {
                var methodID = (MethodID)method.ToInt32();
                switch (methodID)
                {
                    case MethodID.BeginMix:
                    {
                        var champleCount = userData.ToInt32();
                        data.BeginMix(champleCount);
                        break;
                    }
                    case MethodID.EndMix:
                    {
                        UnsafeUtility.CopyPtrToStructure(userData.ToPointer(), out EndMixData endMixData);

                        var length = endMixData.ChannelCount * endMixData.ChampleCount;
                        var nativeBuffer = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<float>(endMixData.Buffer, length, Allocator.Invalid);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
                        NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref nativeBuffer, endMixData.Safety);
#endif
                        var frameCount = endMixData.ChampleCount / endMixData.ChannelCount;

                        data.EndMix(nativeBuffer, frameCount);
                        break;
                    }
                    case MethodID.Dispose:
                    {
                        data.Dispose();
                        break;
                    }
                    case MethodID.Initialize:
                    {
                        var initializationData = (InitializationData*)userData;
                        data.Initialize(initializationData->ChannelCount, initializationData->SoundFormat, initializationData->SampleRate, initializationData->DSPBufferSize);
                        break;
                    }
                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }

19 Source : MainWindow.xaml.cs
with MIT License
from AlexanderPro

private unsafe IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == WM_WINDOWPOSCHANGING)
            {
                var windowPos = Marshal.PtrToStructure<WindowPos>(lParam);
                windowPos.hwndInsertAfter = new IntPtr(HWND_BOTTOM);
                windowPos.flags &= ~(uint)SWP_NOZORDER;
                handled = true;
            }

            if (msg == WM_DPICHANGED)
            {
                var handle = new WindowInteropHelper(this).Handle;
                var rc = (Native.Rect*)lParam.ToPointer();
                SetWindowPos(handle, IntPtr.Zero, 0, 0, rc->Right, rc->Left, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER);
                handled = true;
            }

            return IntPtr.Zero;
        }

19 Source : ExtentHooks.cs
with MIT License
from allisterb

internal static global::jemalloc.ExtentHooks __CreateInstance(global::System.IntPtr native, bool skipVTables = false)
        {
            return new global::jemalloc.ExtentHooks(native.ToPointer(), skipVTables);
        }

19 Source : FixedBuffer.cs
with MIT License
from allisterb

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        internal unsafe ref T Read(int index)
        {
            ref T ret = ref Unsafe.Add(ref Unsafe.AsRef<T>(_Ptr.ToPointer()), index);
            return ref ret;
        }

19 Source : NativeMemory.cs
with MIT License
from allisterb

public override MemoryHandle Pin()
        {
            Retain();
            unsafe
            {
                return new MemoryHandle(this, ptr.ToPointer());
            }
        }

19 Source : HugeBuffer.cs
with MIT License
from allisterb

protected unsafe virtual IntPtr Allocate(ulong length)
        {
            if (length < 0)
                throw new ArgumentOutOfRangeException("length");
            Contract.EndContractBlock();
            ulong s = checked(length * ElementSizeInBytes);
            handle = Jem.Calloc(length, ElementSizeInBytes);
            if (handle != IntPtr.Zero)
            {
                voidPtr = handle.ToPointer();
                Length = length;
                SizeInBytes = s;
                InitSegments();
                InitVectors();
            }
            return handle;
        }

19 Source : MallocVsArray.cs
with MIT License
from allisterb

[Benchmark(Description = "Malloc buffer and Span<T> on the system managed heap.")]
        [BenchmarkCategory("Create")]
        public void CreateSpan()
        {
            ulong msize = (ulong)(ArraySize * JemUtil.SizeOfStruct<T>());
            IntPtr ptr = Jem.Malloc(msize);
            unsafe
            {
                Span<T> s = new Span<T>(ptr.ToPointer(), ArraySize);
            }
            SetMemoryStatistics();
            Jem.Free(ptr);
        }

19 Source : common.cs
with MIT License
from allisterb

internal static global::IntelMKL.MKL_Complex8 __CreateInstance(global::System.IntPtr native, bool skipVTables = false)
        {
            return new global::IntelMKL.MKL_Complex8(native.ToPointer(), skipVTables);
        }

19 Source : common.cs
with MIT License
from allisterb

internal static global::IntelMKL.MKL_Complex16 __CreateInstance(global::System.IntPtr native, bool skipVTables = false)
        {
            return new global::IntelMKL.MKL_Complex16(native.ToPointer(), skipVTables);
        }

19 Source : common.cs
with MIT License
from allisterb

internal static global::IntelMKL.MKLVersion __CreateInstance(global::System.IntPtr native, bool skipVTables = false)
        {
            return new global::IntelMKL.MKLVersion(native.ToPointer(), skipVTables);
        }

19 Source : ExtentHooks.cs
with MIT License
from allisterb

private static void* __CopyValue(global::jemalloc.ExtentHooks.__Internal native)
        {
            var ret = Marshal.AllocHGlobal(sizeof(global::jemalloc.ExtentHooks.__Internal));
            *(global::jemalloc.ExtentHooks.__Internal*)ret = native;
            return ret.ToPointer();
        }

19 Source : HugeBuffer.cs
with MIT License
from allisterb

public unsafe void Fill(T value)
        {
            ThrowIfNotAllocatedOrInvalid();
            for (int i = 0; i < segments.Length; i++)
            {
                Span<T> s = new Span<T>(segments2[i].Item1.ToPointer(), segments2[i].Item2);
                s.Fill(value);
            }
        }

19 Source : HugeBuffer.cs
with MIT License
from allisterb

public unsafe Vector<T> GetSlicereplacedingleVector(ulong index)
        {
            ThrowIfNotAllocatedOrInvalid();
            ThrowIfIndexOutOfRange(index);
            if ((Length - index) < (ulong) VectorLength)
            {
                BufferIsNotVectorisable();
            }
            int i = _GetSegmentIndex(index);
            _GetSegment(index, out void* ptr, out int offset);
            IntPtr start = BufferHelpers.Add<T>(segments2[i].Item1, offset);
            return Unsafe.Read<Vector<T>>(start.ToPointer());
        }

19 Source : Buffer.cs
with MIT License
from allisterb

private unsafe bool Allocate(int length)
        {
            _Ptr = Jem.Calloc((ulong) length, ElementSizeInBytes);
            if (_Ptr != IntPtr.Zero)
            {
                _Length = length;
                _SizeInBytes = (ulong)_Length * ElementSizeInBytes;
                _Timestamp = DateTime.Now.Ticks;
                _VoidPointer = _Ptr.ToPointer();
                _Span = new Span<T>(_VoidPointer, _Length);
                return true;
            }
            else return false;
        }

19 Source : FixedBuffer.cs
with MIT License
from allisterb

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public unsafe ReadOnlySpan<Vector<T>> AcquireVectorSpan()
        {
            ThrowIfNotVectorizable();
            ThrowIfInvalid();
            return new ReadOnlySpan<Vector<T>>(_Ptr.ToPointer(), _Length / JemUtil.VectorLength<T>());
        }

19 Source : FixedBuffer.cs
with MIT License
from allisterb

public unsafe Span<Vector<T>> AcquireVectorWriteSpan()
        {
            ThrowIfNotVectorizable();
            Acquire();
            return new Span<Vector<T>>(_Ptr.ToPointer(), _Length / JemUtil.VectorLength<T>());
        }

19 Source : HugeBuffer.cs
with MIT License
from allisterb

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        protected unsafe void _GetSegment(ulong index, out void* ptr, out int offset)
        {
            int s = _GetSegmentIndex(index);
            int l = segments.Length;
            ptr = segments[s].ToPointer();
            offset = (int)(index - ((ulong)(s) * Int32.MaxValue));
        }

19 Source : HugeBuffer.cs
with MIT License
from allisterb

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        protected unsafe Span<T> _GetSegmentSpan(ulong index)
        {
            int i = _GetSegmentIndex(index);
            return new Span<T>(segments2[i].Item1.ToPointer(), segments2[i].Item2);
        }

19 Source : HugeBuffer.cs
with MIT License
from allisterb

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        protected unsafe Span<Vector<T>> _GetSegmentVectorSpan(ulong index)
        {
            int i = _GetSegmentIndex(index);
            return new Span<Vector<T>>(segments2[i].Item1.ToPointer(), segments2[i].Item2 / VectorLength + 1);
        }

19 Source : HugeBuffer.cs
with MIT License
from allisterb

public unsafe Vector<T> GetreplacedingleVector()
        {
            ThrowIfNotAllocatedOrInvalid();
            if (this.Length != (ulong) VectorLength)
            {
                throw new InvalidOperationException($"The length of the array must be {Vector<T>.Count} elements to create a vector of type {CLRType.Name}.");
            }
            return Unsafe.Read<Vector<T>>(handle.ToPointer());
        }

19 Source : HugeBuffer.cs
with MIT License
from allisterb

public unsafe Span<Vector<T>> GetSliceSegmentAsVectorSpan(ulong index)
        {
            ThrowIfNotAllocatedOrInvalid();
            if ((Length - index) < (ulong) VectorLength)
            {
                ThrowIfIndexOutOfRange(index);
            }
            T v = this[index];
            int i = _GetSegmentIndex(index);
            if (segments2[i].Item2 % VectorLength != 0)
            {
                BufferIsNotVectorisable();
            }
            return new Span<Vector<T>>(segments2[i].Item1.ToPointer(), segments2[i].Item2 / VectorLength + 1);
        }

19 Source : SafeBuffer.cs
with MIT License
from allisterb

protected unsafe virtual IntPtr Allocate(int length)
        {
            if (length <= 0)
                throw new ArgumentOutOfRangeException("length");
            Contract.EndContractBlock();
            ulong s = checked((uint)length * ElementSizeInBytes);
            handle = Jem.Calloc((uint)length, ElementSizeInBytes);
            if (handle != IntPtr.Zero)
            {
                voidPtr = handle.ToPointer();
                Length = length;
                SizeInBytes = s;
                InitVector();
            }
            return handle;
        }

19 Source : Program.cs
with MIT License
from altimesh

[IntrinsicFunction("malloc")]
        public static void* malloc(int size)
        {
            return Marshal.AllocHGlobal(size).ToPointer();
        }

19 Source : IWICBitmapLock.cs
with MIT License
from amerkoleci

public unsafe Span<T> GetDataPointer<T>() where T : unmanaged
        {
            IntPtr pointer = GetDataPointer(out int size);
            return new Span<T>(pointer.ToPointer(), size / sizeof(T));
        }

19 Source : BuildRaytracingAccelerationStructureInputs.cs
with MIT License
from amerkoleci

internal unsafe void __MarshalFrom(ref __Native @ref)
        {
            Type = @ref.Type;
            Flags = @ref.Flags;
            DescriptorsCount = @ref.NumDescs;
            Layout = @ref.DescsLayout;

            if (@ref.NumDescs > 0)
            {
                if (@ref.Type == RaytracingAccelerationStructureType.TopLevel)
                {
                    InstanceDescriptions = Unsafe.Read<long>(@ref.Union.pGeometryDescs.ToPointer());
                }
                else
                {
                    GeometryDescriptions = new RaytracingGeometryDescription[@ref.NumDescs];
                    UnsafeUtilities.Read(@ref.Union.pGeometryDescs, GeometryDescriptions);
                }
            }
        }

19 Source : DxilLibraryDescription.cs
with MIT License
from amerkoleci

unsafe void IStateSubObjectDescriptionMarshal.__MarshalFree(ref IntPtr pDesc)
        {
            ref __Native nativeLibrary = ref Unsafe.AsRef<__Native>(pDesc.ToPointer());
            DxilLibrary.__MarshalFree(ref nativeLibrary.DXILLibrary);

            if (nativeLibrary.pExports != null)
            {
                for (int i = 0; i < nativeLibrary.NumExports; i++)
                {
                    Exports[i].__MarshalFree(ref nativeLibrary.pExports[i]);
                }

                Marshal.FreeHGlobal((IntPtr)nativeLibrary.pExports);
            }

            Marshal.FreeHGlobal(pDesc);
        }

19 Source : DxilSubObjectToExportsAssociation.cs
with MIT License
from amerkoleci

unsafe void IStateSubObjectDescriptionMarshal.__MarshalFree(ref IntPtr pDesc)
        {
            ref __Native native = ref Unsafe.AsRef<__Native>(pDesc.ToPointer());
            Marshal.FreeHGlobal(native.pSubobjectToreplacedociate);

            if (native.NumExports > 0)
            {
                for (int i = 0; i < native.NumExports; i++)
                {
                    Marshal.FreeHGlobal(native.pExports[i]);
                }

                Marshal.FreeHGlobal(new IntPtr(native.pExports));
            }

            Marshal.FreeHGlobal(pDesc);
        }

See More Examples