/ Published in: C#
You must include these DLL references in your vsweb or vscode project:\r\nPresentationCore,\r\nPresentationFramework,\r\nWindowsBase. \r\nNotice how I am manipulating the RGB values of each pixel, this is the power of these classes. The Drawing classes have the pixel drawing capabilities to draw lines and such already written for you, but handling a grayscale byte for byte is faster than relying on their other classes. I also chose to load and encode as PNG, but they have loaders and encoders for other file types as well that work the same way.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
using System; using System.IO; using System.Windows.Media.Imaging; using System.Windows.Media; namespace MyNamespace.Imaging { public sealed partial class MyImageClass { public enum eBpp : byte { _1 = 0, _8 = 1, _16 = 2, _24 = 3, _32 = 4, _40 = 5, _48 = 6, _56 = 7, _64 = 8, _128 = 16 } protected static BitmapSource LoadPng(string fileName) { FileStream fs = File.OpenRead(fileName); fs.Read(data, 0, (int)fs.Length); fs.Close(); PngBitmapDecoder decoder = new PngBitmapDecoder(ms, BitmapCreateOptions.None, BitmapCacheOption.None); return decoder.Frames[0]; } protected static void MakeGrayScale(ref BitmapSource image) { int stride = image.PixelWidth * bytes; long size = image.PixelHeight * stride; image.CopyPixels(source, stride, 0); if (image.Format.BitsPerPixel == 32) { for (int i = bytes - 1; i < size; i += bytes) { uint avrg = (uint)source[i - 3] + (uint)source[i - 2] + (uint)source[i - 1]; if (avrg != 0) avrg = avrg / 3; dest[i - 3] = (byte)avrg; dest[i - 2] = (byte)avrg; dest[i - 1] = (byte)avrg; dest[i] = source[i]; //alpha } } //aren't handling any other types than 32bit color, but these can be added easily image = BitmapSource.Create(image.PixelWidth, image.PixelHeight, 96, 96, image.Format, BitmapPalettes.Halftone256Transparent, dest, stride); } protected static MemoryStream PngEncode(BitmapSource image) { //encode image as png encoder.Interlace = PngInterlaceOption.On; encoder.Frames.Add(BitmapFrame.Create(image)); encoder.Save(ret); ret.Position = 0; return ret; } } }