public static BitmapImage Create(int pixelWidth, int pixelHeight, double dpiX, double dpiY, PixelFormat pixelFormat, BitmapPalette palette, Array pixels, int stride) { throw new NotImplementedException(); }
public CreateIndexedBitmap() { Title = "Create Indexed Bitmap"; // Create palette with 256 colors combining red and blue. List<Color> colors = new List<Color>(); for (int r = 0; r < 256; r += 17) for (int b = 0; b < 256; b += 17) colors.Add(Color.FromRgb((byte)r, 0, (byte)b)); BitmapPalette palette = new BitmapPalette(colors); // Create bitmap bit array byte[] array = new byte[256 * 256]; for (int x = 0; x < 256; x++) for (int y = 0; y < 256; y++) array[256 * y + x] = (byte)(((int)Math.Round(y / 17.0) << 4) | (int)Math.Round(x / 17.0)); // Create bitmap. BitmapSource bitmap = BitmapSource.Create(256, 256, 96, 96, PixelFormats.Indexed8, palette, array, 256); // Create an Image object and set its Source to the bitmap. Image img = new Image(); img.Source = bitmap; // Make the Image object the content of the window. Content = img; }
public ScreenAdapter(ZXSpectrum.Screen zxScreen) { this.zxScreen = zxScreen; // Initialize the ZX Spectrum color palette IList<Color> zxColors = new List<Color>(); zxColors.Add(Color.FromRgb(0x00, 0x00, 0x00)); // black -- (bright 0) -- zxColors.Add(Color.FromRgb(0x00, 0x00, 0xCD)); // blue zxColors.Add(Color.FromRgb(0xCD, 0x00, 0x00)); // red zxColors.Add(Color.FromRgb(0xCD, 0x00, 0xCD)); // magenta zxColors.Add(Color.FromRgb(0x00, 0xCD, 0x00)); // green zxColors.Add(Color.FromRgb(0x00, 0xCD, 0xCD)); // cyan zxColors.Add(Color.FromRgb(0xCD, 0xCD, 0x00)); // yellow zxColors.Add(Color.FromRgb(0xCD, 0xCD, 0xCD)); // white zxColors.Add(Color.FromRgb(0x00, 0x00, 0x00)); // black -- (bright 1) -- zxColors.Add(Color.FromRgb(0x00, 0x00, 0xFF)); // blue zxColors.Add(Color.FromRgb(0xFF, 0x00, 0x00)); // red zxColors.Add(Color.FromRgb(0xFF, 0x00, 0xFF)); // magenta zxColors.Add(Color.FromRgb(0x00, 0xFF, 0x00)); // green zxColors.Add(Color.FromRgb(0x00, 0xFF, 0xFF)); // cyan zxColors.Add(Color.FromRgb(0xFF, 0xFF, 0x00)); // yellow zxColors.Add(Color.FromRgb(0xFF, 0xFF, 0xFF)); // white BitmapPalette zxPalette = new BitmapPalette(zxColors); // Initialize a writeable bitmap to draw the zx screen, and display it through an image zxScreenBitmap = new WriteableBitmap(ZXSpectrum.Screen.WIDTH, ZXSpectrum.Screen.HEIGHT, 96, 96, PixelFormats.Indexed4, zxPalette); }
/// <summary> /// MatをBitmapSourceに変換する. /// </summary> /// <param name="src">変換するIplImage</param> /// <param name="horizontalResolution"></param> /// <param name="verticalResolution"></param> /// <param name="pixelFormat"></param> /// <param name="palette"></param> /// <returns>WPFのBitmapSource</returns> #else /// <summary> /// Converts Mat to BitmapSource. /// </summary> /// <param name="src">Input IplImage</param> /// <param name="horizontalResolution"></param> /// <param name="verticalResolution"></param> /// <param name="pixelFormat"></param> /// <param name="palette"></param> /// <returns>BitmapSource</returns> #endif public static BitmapSource ToBitmapSource( this Mat src, int horizontalResolution, int verticalResolution, PixelFormat pixelFormat, BitmapPalette palette) { if (src == null) throw new ArgumentNullException("src"); if (src.IsDisposed) throw new ObjectDisposedException(typeof(Mat).ToString()); if (src.Dims() != 2) throw new ArgumentException("src.Dims() != 2"); long step = src.Step(); return BitmapSource.Create( src.Width, src.Height, horizontalResolution, verticalResolution, pixelFormat, palette, src.Data, (int)(step * src.Rows), (int)step); }
public CreateIndexedBitmap() { Title = "Create Indexed Bitmap"; // 256���� ���� ���� List<Color> colors = new List<Color>(); for (int r = 0; r < 256; r += 17) for (int b = 0; b < 256; b += 17) colors.Add(Color.FromRgb((byte)r, 0, (byte)b)); // ������ ������ �ȷ�Ʈ ��ü�� �߰� BitmapPalette palette = new BitmapPalette(colors); // ��Ʈ�� ��Ʈ �迭 ���� byte[] array = new byte[256 * 256]; for (int x = 0; x < 256; x++) for (int y = 0; y < 256; y++) array[256 * y + x] = (byte)(((int)Math.Round(y / 17.0) << 4) | (int)Math.Round(x / 17.0)); // ��Ʈ�� ���� BitmapSource bitmap = BitmapSource.Create(256, 256, 96, 96, PixelFormats.Indexed8, palette, array, 256); Image img = new Image(); img.Source = bitmap; Content = img; }
private void CreateBitmapByBitmapSource() { // Use BitmapSource to create a bitmap. List<Color> colors = new List<Color>(); for (Int32 r = 0; r < 256; r += 17) { for (Int32 b = 0; b < 256; b += 17) { colors.Add(Color.FromRgb((byte)r, 0, (byte)b)); } } BitmapPalette palette = new BitmapPalette(colors); byte[] array = new byte[256 * 256]; for (Int32 x = 0; x < 256; x++) { for (Int32 y = 0; y < 256; y++) { array[256 * y + x] = (byte)(((Int32)Math.Round(y / 17.0) << 4) | (Int32)Math.Round(x / 17.0)); } } BitmapSource bitmapSource = BitmapSource.Create(256, 256, 96, 96, PixelFormats.Indexed8, palette, array, 256); Image img = new Image(); img.Source = bitmapSource; Content = img; }
public static BitmapSource Create(int pixelWidth, int pixelHeight, double dpiX, double dpiY, PixelFormat pixelFormat, BitmapPalette palette, IntPtr buffer, int bufferSize, int stride) { throw new NotImplementedException(); }
public MemoryStream ReduceColorDepth(Bitmap bmp) { var ms = new MemoryStream(); bmp.Save(ms, ImageFormat.Png); var bi = new BitmapImage(); bi.BeginInit(); bi.StreamSource = ms; bi.EndInit(); var newFormatedBitmapSource = new FormatConvertedBitmap(); newFormatedBitmapSource.BeginInit(); newFormatedBitmapSource.Source = bi; var myPalette = new BitmapPalette(bi, 256); newFormatedBitmapSource.DestinationPalette = myPalette; //Set PixelFormats newFormatedBitmapSource.DestinationFormat = PixelFormats.Indexed8; newFormatedBitmapSource.EndInit(); var pngBitmapEncoder = new PngBitmapEncoder(); pngBitmapEncoder.Interlace = PngInterlaceOption.Off; pngBitmapEncoder.Frames.Add(BitmapFrame.Create(newFormatedBitmapSource)); var memstream = new MemoryStream(); pngBitmapEncoder.Save(memstream); memstream.Position = 0; return memstream; }
/// <summary> /// Конвертация BitmapSource в другой формат BitmapSource. /// </summary> /// <param name="source">Источник для конвертации.</param> /// <param name="destinationFormat">Новый формат.</param> /// <param name="destinationPalette"> /// Палитра для нового формата, если конечно она нужна для нового формата, иначе передать null. /// </param> /// <returns>BitmapSource в новом формате.</returns> public static BitmapSource ConvertTo( this BitmapSource source, PixelFormat destinationFormat, BitmapPalette destinationPalette) { return new FormatConvertedBitmap( source, destinationFormat, destinationPalette, 0); }
public static BitmapSource BuildOptTexture(Texture texture, int paletteIndex = TextureUtils.DefaultPalette, int level = 0) { if (texture == null || paletteIndex < 0 || paletteIndex > 15 || level < 0 || level >= texture.MipmapsCount) return null; int bpp = texture.BitsPerPixel; if (bpp == 8) { var palette = new BitmapPalette(Enumerable.Range(0, 256) .Select(i => { ushort c = BitConverter.ToUInt16(texture.Palette, paletteIndex * 512 + i * 2); byte r = (byte)((c & 0xF800) >> 11); byte g = (byte)((c & 0x7E0) >> 5); byte b = (byte)(c & 0x1F); r = (byte)((r * (0xffU * 2) + 0x1fU) / (0x1fU * 2)); g = (byte)((g * (0xffU * 2) + 0x3fU) / (0x3fU * 2)); b = (byte)((b * (0xffU * 2) + 0x1fU) / (0x1fU * 2)); return Color.FromRgb(r, g, b); }) .ToList()); int texWidth; int texHeight; byte[] texImageData = texture.GetMipmapImageData(level, out texWidth, out texHeight); int size = texWidth * texHeight; byte[] imageData = new byte[size * 4]; for (int i = 0; i < size; i++) { int colorIndex = texImageData[i]; imageData[i * 4 + 0] = palette.Colors[colorIndex].B; imageData[i * 4 + 1] = palette.Colors[colorIndex].G; imageData[i * 4 + 2] = palette.Colors[colorIndex].R; imageData[i * 4 + 3] = texture.AlphaData == null ? (byte)255 : texture.AlphaData[i]; } return BitmapSource.Create(texWidth, texHeight, 96, 96, PixelFormats.Bgra32, null, imageData, texWidth * 4); } else if (bpp == 32) { int texWidth; int texHeight; byte[] texImageData = texture.GetMipmapImageData(level, out texWidth, out texHeight); return BitmapSource.Create(texWidth, texHeight, 96, 96, PixelFormats.Bgra32, null, texImageData, texWidth * 4); } else { return null; } }
/// <summary> /// MatをBitmapSourceに変換する. /// </summary> /// <param name="src">変換するIplImage</param> /// <param name="horizontalResolution"></param> /// <param name="verticalResolution"></param> /// <param name="pixelFormat"></param> /// <param name="palette"></param> /// <returns>WPFのBitmapSource</returns> #else /// <summary> /// Converts Mat to BitmapSource. /// </summary> /// <param name="src">Input IplImage</param> /// <param name="horizontalResolution"></param> /// <param name="verticalResolution"></param> /// <param name="pixelFormat"></param> /// <param name="palette"></param> /// <returns>BitmapSource</returns> #endif public static BitmapSource ToBitmapSource( this Mat src, int horizontalResolution, int verticalResolution, PixelFormat pixelFormat, BitmapPalette palette) { return src.ToWriteableBitmap(horizontalResolution, verticalResolution, pixelFormat, palette); }
public override ImageData Read(Stream file, ImageMetaData info) { file.Position = 0x14; using (var reader = new Reader (file, info)) { reader.Unpack(); var palette = new BitmapPalette (reader.Palette); return ImageData.Create (info, PixelFormats.Indexed8, palette, reader.Data, (int)info.Width); } }
private void EnsureThumbnail() { if (_isThumbnailCached || IsDownloading) { return; } else { EnsureSource(); IntPtr /* IWICBitmapSource */ thumbnail = IntPtr.Zero; lock (_syncObject) { // Check if there is embedded thumbnail or not int hr = UnsafeNativeMethods.WICBitmapFrameDecode.GetThumbnail( _frameSource, out thumbnail ); if (hr != (int)WinCodecErrors.WINCODEC_ERR_CODECNOTHUMBNAIL) { HRESULT.Check(hr); } } _isThumbnailCached = true; if (thumbnail != IntPtr.Zero) { BitmapSourceSafeMILHandle thumbHandle = new BitmapSourceSafeMILHandle(thumbnail); SafeMILHandle unmanagedPalette = BitmapPalette.CreateInternalPalette(); BitmapPalette palette = null; int hr = UnsafeNativeMethods.WICBitmapSource.CopyPalette( thumbHandle, unmanagedPalette ); if (hr == HRESULT.S_OK) { palette = new BitmapPalette(unmanagedPalette); } _thumbnail = new UnmanagedBitmapWrapper( CreateCachedBitmap( null, thumbHandle, BitmapCreateOptions.PreservePixelFormat, _cacheOption, palette )); _thumbnail.Freeze(); } } }
/// <summary> /// Called to draw on screen /// </summary> /// <param name="drawingContext">The drawind context in which we can draw</param> protected override void OnRender(System.Windows.Media.DrawingContext drawingContext) { // only set the pallette once (dont do in constructor as causes odd errors if exception occurs) if (_pallette == null) _pallette = SetupFirePalette(); _fireGenerator.UpdateFire(); BitmapSource bs = BitmapSource.Create(_fireGenerator.Width, _fireGenerator.Height, DPI, DPI, PixelFormats.Indexed8, _pallette, _fireGenerator.FireData, _fireGenerator.Width); drawingContext.DrawImage(bs, new Rect(0, 0, this.DesiredSize.Width, this.DesiredSize.Height)); }
public override ImageData Read(Stream stream, ImageMetaData info) { var meta = info as Ed8MetaData; if (null == meta) throw new ArgumentException ("Ed8Format.Read should be supplied with Ed8MetaData", "info"); stream.Position = 0x1a; var reader = new Reader (stream, meta); reader.Unpack(); var palette = new BitmapPalette (reader.Palette); return ImageData.Create (info, PixelFormats.Indexed8, palette, reader.Data, (int)info.Width); }
public DrawingSettings(int pixelWidth, int pixelHeight, double dpiX, double dpiY, PixelFormat pixelFormat, BitmapPalette palette, int stride) { PixelWidth = pixelWidth; PixelHeight = pixelHeight; DpiX = dpiX; DpiY = dpiY; PixelFromatUsed = pixelFormat; BitmapPalleteUsed = palette; Stride = stride; }
public Arrangement(byte[] arrangementData, byte[] graphicsData, byte[] paletteData, byte bitsPerPixel, String name, Boolean GBA) { this.arrangementData = new ushort[arrangementData.Length/2+1]; Buffer.BlockCopy(arrangementData, 0, this.arrangementData, 0, arrangementData.Length); this.graphicsData = graphicsData; this.bitsPerPixel = bitsPerPixel; this.Name = name; this.GBA = GBA; this.paletteData = new ushort[paletteData.Length / 2]; Buffer.BlockCopy(paletteData, 0, this.paletteData, 0, paletteData.Length); List<System.Windows.Media.Color> colors = new List<System.Windows.Media.Color>(); for (int i = 0; i < this.paletteData.Length; i++) colors.Add(System.Windows.Media.Color.FromArgb((byte)((i == 0) ? 0 : 255), (byte)((this.paletteData[i] & 31) << 3), (byte)((this.paletteData[i] & 0x3E0) >> 2), (byte)((this.paletteData[i] & 0x7C00) >> 7))); palette = new BitmapPalette(colors); }
/// Returns if the Palette has any alpha within its colors internal static bool DoesPaletteHaveAlpha(BitmapPalette palette) { if (palette != null) { foreach (Color color in palette.Colors) { if (color.A != 255) { return(true); } } } return(false); }
void SetPalette() { var old = Control; // re-create with new palette var colors = new List <swm.Color> (numColors); for (int i = 0; i < numColors; i++) { colors.Add(palette[i].ToWpf()); } var bufferSize = old.BackBufferStride * old.PixelHeight; var pal = new swmi.BitmapPalette(colors); var bs = swmi.BitmapSource.Create(old.PixelWidth, old.PixelHeight, 96, 96, old.Format, pal, old.BackBuffer, bufferSize, old.BackBufferStride); Control = new swmi.WriteableBitmap(bs); }
public BitmapSource CreateBitmap(IDisplay display) { var pixels = new byte[64*32]; for (var y = 0; y < 32; y++) { for (var x = 0; x < 64; x++) { var offset = y * 64 + x; var pixel = display.Pixels[offset]; pixels[offset] = pixel; } } var bitmapPalette = new BitmapPalette(new List<Color> {Colors.DarkBlue, Colors.CornflowerBlue}); return BitmapSource.Create(64, 32, 96, 96, PixelFormats.Indexed8, bitmapPalette, pixels, 64); }
static internal BitmapPalette CreateFromBitmapSource(BitmapSource source) { Debug.Assert(source != null); SafeMILHandle bitmapSource = source.WicSourceHandle; Debug.Assert(bitmapSource != null && !bitmapSource.IsInvalid); SafeMILHandle unmanagedPalette = CreateInternalPalette(); BitmapPalette palette; // Don't throw on the HRESULT from this method. If it returns failure, // that likely means that the source doesn't have a palette. lock (source.SyncObject) { int hr = UnsafeNativeMethods.WICBitmapSource.CopyPalette( bitmapSource, unmanagedPalette); if (hr != HRESULT.S_OK) { return(null); } } WICPaletteType paletteType; bool hasAlpha; HRESULT.Check(UnsafeNativeMethods.WICPalette.GetType(unmanagedPalette, out paletteType)); HRESULT.Check(UnsafeNativeMethods.WICPalette.HasAlpha(unmanagedPalette, out hasAlpha)); if (paletteType == WICPaletteType.WICPaletteTypeCustom || paletteType == WICPaletteType.WICPaletteTypeOptimal) { palette = new BitmapPalette(unmanagedPalette); } else { palette = BitmapPalettes.FromMILPaletteType(paletteType, hasAlpha); Debug.Assert(palette != null); } return(palette); }
// BitmapSource generation code coutesy of http://social.msdn.microsoft.com/forums/en-US/wpf/thread/56364b28-1277-4be8-8d45-78788cc4f2d7/ void GenerateNoiseBitmap() { if (Colors == null || Colors.Count == 0) { SetValue(noiseImageKey, null); return; } try { var rnd = new Random(); var colors = Colors.Select(value => value.Color).ToList(); var totalFrequency = Colors.Sum(a => a.Frequency); var frequencyMap = GetFrequencyMap(); BitmapPalette palette = new BitmapPalette(colors); PixelFormat pf = PixelFormats.Bgra32; int width = Size; int height = width; int stride = (width * pf.BitsPerPixel) / 8; byte[] pixels = new byte[height * stride]; for (int i = 0; i < height * stride; i += (pf.BitsPerPixel / 8)) { var color = GetWeightedRandomColor(totalFrequency, frequencyMap, rnd); pixels[i] = color.B; pixels[i + 1] = color.G; pixels[i + 2] = color.R; pixels[i + 3] = color.A; } var image = BitmapSource.Create(width, height, 96, 96, pf, palette, pixels, stride); SetValue(noiseImageKey, image); } catch (ArgumentException) { } }
unsafe internal CachedBitmap( int pixelWidth, int pixelHeight, double dpiX, double dpiY, PixelFormat pixelFormat, BitmapPalette palette, IntPtr buffer, int bufferSize, int stride ) : base(true) // Use base class virtuals { InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, buffer, bufferSize, stride); }
unsafe internal CachedBitmap( int pixelWidth, int pixelHeight, double dpiX, double dpiY, PixelFormat pixelFormat, BitmapPalette palette, IntPtr buffer, int bufferSize, int stride ) : base(true) // Use base class virtuals { InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, buffer, bufferSize, stride); }
/// <summary> /// Construct a FormatConvertedBitmap /// </summary> /// <param name="source">BitmapSource to apply to the format conversion to</param> /// <param name="destinationFormat">Destionation Format to apply to the bitmap</param> /// <param name="destinationPalette">Palette if format is palettized</param> /// <param name="alphaThreshold">Alpha threshold</param> public FormatConvertedBitmap(BitmapSource source, PixelFormat destinationFormat, BitmapPalette destinationPalette, double alphaThreshold) : base(true) // Use base class virtuals { if (source == null) { throw new ArgumentNullException("source"); } if (alphaThreshold < (double)(0.0) || alphaThreshold > (double)(100.0)) { throw new ArgumentException(SR.Get(SRID.Image_AlphaThresholdOutOfRange)); } _bitmapInit.BeginInit(); Source = source; DestinationFormat = destinationFormat; DestinationPalette = destinationPalette; AlphaThreshold = alphaThreshold; _bitmapInit.EndInit(); FinalizeCreation(); }
/// <summary> /// Construct a FormatConvertedBitmap /// </summary> /// <param name="source">BitmapSource to apply to the format conversion to</param> /// <param name="destinationFormat">Destionation Format to apply to the bitmap</param> /// <param name="destinationPalette">Palette if format is palettized</param> /// <param name="alphaThreshold">Alpha threshold</param> public FormatConvertedBitmap(BitmapSource source, PixelFormat destinationFormat, BitmapPalette destinationPalette, double alphaThreshold) : base(true) // Use base class virtuals { if (source == null) { throw new ArgumentNullException("source"); } if (alphaThreshold < (double)(0.0) || alphaThreshold > (double)(100.0)) { throw new ArgumentException(SR.Get(SRID.Image_AlphaThresholdOutOfRange)); } _bitmapInit.BeginInit(); Source = source; DestinationFormat = destinationFormat; DestinationPalette = destinationPalette; AlphaThreshold = alphaThreshold; _bitmapInit.EndInit(); FinalizeCreation(); }
/// <summary> /// IplImageをBitmapSourceに変換する. /// </summary> /// <param name="src">変換するIplImage</param> /// <param name="horizontalResolution"></param> /// <param name="verticalResolution"></param> /// <param name="pixelFormat"></param> /// <param name="palette"></param> /// <returns>WPFのBitmapSource</returns> #else /// <summary> /// Converts IplImage to BitmapSource. /// </summary> /// <param name="src">Input IplImage</param> /// <param name="horizontalResolution"></param> /// <param name="verticalResolution"></param> /// <param name="pixelFormat"></param> /// <param name="palette"></param> /// <returns>BitmapSource</returns> #endif public static BitmapSource ToBitmapSource( this IplImage src, int horizontalResolution, int verticalResolution, PixelFormat pixelFormat, BitmapPalette palette) { if (src == null) throw new ArgumentNullException("src"); if (src.IsDisposed) throw new ObjectDisposedException(typeof(IplImage).ToString()); return BitmapSource.Create( src.Width, src.Height, horizontalResolution, verticalResolution, pixelFormat, palette, src.ImageData, src.WidthStep * src.Height, src.WidthStep); }
internal static BitmapSourceSafeMILHandle CreateCachedBitmap( BitmapFrame frame, BitmapSourceSafeMILHandle wicSource, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption, BitmapPalette palette ) { BitmapSourceSafeMILHandle wicConverter = null; BitmapSourceSafeMILHandle wicConvertedSource = null; // For NoCache, return the original if (cacheOption == BitmapCacheOption.None) { return wicSource; } using (FactoryMaker factoryMaker = new FactoryMaker()) { IntPtr wicFactory = factoryMaker.ImagingFactoryPtr; bool changeFormat = false; PixelFormat originalFmt = PixelFormats.Pbgra32; WICBitmapCreateCacheOptions wicCache = WICBitmapCreateCacheOptions.WICBitmapCacheOnLoad; if (cacheOption == BitmapCacheOption.OnDemand) { wicCache = WICBitmapCreateCacheOptions.WICBitmapCacheOnDemand; } originalFmt = PixelFormat.GetPixelFormat(wicSource); PixelFormat destFmt = originalFmt; // check that we need to change the format of the bitmap if (0 == (createOptions & BitmapCreateOptions.PreservePixelFormat)) { if (!IsCompatibleFormat(originalFmt)) changeFormat = true; destFmt = BitmapSource.GetClosestDUCEFormat(originalFmt, palette); } if (frame != null && (createOptions & BitmapCreateOptions.IgnoreColorProfile) == 0 && frame.ColorContexts != null && frame.ColorContexts[0] != null && frame.ColorContexts[0].IsValid && !frame._isColorCorrected && PixelFormat.GetPixelFormat(wicSource).Format != PixelFormatEnum.Extended ) { ColorContext destinationColorContext; // We need to make sure, we can actually create the ColorContext for the destination destFmt // If the destFmt is gray or scRGB, the following is not supported, so we cannot // create the ColorConvertedBitmap try { destinationColorContext = new ColorContext(destFmt); } catch (NotSupportedException) { destinationColorContext = null; } if (destinationColorContext != null) { // NOTE: Never do this for a non-MIL pixel format, because the format converter has // special knowledge to deal with the profile bool conversionSuccess = false; bool badColorContext = false; // First try if the color converter can handle the source format directly // Its possible that the color converter does not support certain pixelformats, so put a try/catch here. try { ColorConvertedBitmap colorConvertedBitmap = new ColorConvertedBitmap( frame, frame.ColorContexts[0], destinationColorContext, destFmt ); wicSource = colorConvertedBitmap.WicSourceHandle; frame._isColorCorrected = true; conversionSuccess = true; changeFormat = false; // Changeformat no longer necessary, because destFmt already created // by ColorConvertedBitmap } catch (NotSupportedException) { } catch (FileFormatException) { // If the file contains a bad color context, we catch the exception here // and don't bother trying the color conversion below, since color transform isn't possible // with the given color context. badColorContext = true; } if (!conversionSuccess && changeFormat && !badColorContext) { // If the conversion failed, we first use // a FormatConvertedBitmap, and then Color Convert that one... changeFormat = false; FormatConvertedBitmap formatConvertedBitmap = new FormatConvertedBitmap(frame, destFmt, null, 0.0); ColorConvertedBitmap colorConvertedBitmap = new ColorConvertedBitmap( formatConvertedBitmap, frame.ColorContexts[0], destinationColorContext, destFmt ); wicSource = colorConvertedBitmap.WicSourceHandle; frame._isColorCorrected = true; Debug.Assert(destFmt == colorConvertedBitmap.Format); changeFormat = false; // Changeformat no longer necessary, because destFmt already created // by ColorConvertedBitmap } } } if (changeFormat) { // start up a format converter Guid fmtDestFmt = destFmt.Guid; HRESULT.Check(UnsafeNativeMethods.WICCodec.WICConvertBitmapSource( ref fmtDestFmt, wicSource, out wicConverter)); // dump the converted contents into a bitmap HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateBitmapFromSource( wicFactory, wicConverter, wicCache, out wicConvertedSource)); } else { // Create the unmanaged resources HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateBitmapFromSource( wicFactory, wicSource, wicCache, out wicConvertedSource)); } wicConvertedSource.CalculateSize(); } return wicConvertedSource; }
/// Returns the closest format that is supported by the rendering engine internal static PixelFormat GetClosestDUCEFormat(PixelFormat format, BitmapPalette palette) { int i = Array.IndexOf(s_supportedDUCEFormats, format); if (i != -1) { return s_supportedDUCEFormats[i]; } int bitsPerPixel = format.InternalBitsPerPixel; if (bitsPerPixel == 1) { return PixelFormats.Indexed1; } else if (bitsPerPixel == 2) { return PixelFormats.Indexed2; } else if (bitsPerPixel <= 4) { return PixelFormats.Indexed4; } else if (bitsPerPixel <= 8) { return PixelFormats.Indexed8; } else if (bitsPerPixel <= 16 && format.Format != PixelFormatEnum.Gray16) // For Gray16, one of the RGB Formats is closest { return PixelFormats.Bgr555; } else if (format.HasAlpha || BitmapPalette.DoesPaletteHaveAlpha(palette)) { return PixelFormats.Pbgra32; } else { return PixelFormats.Bgr32; } }
private void EnsureThumbnail() { if (_isThumbnailCached || IsDownloading) { return; } else { EnsureSource(); IntPtr /* IWICBitmapSource */ thumbnail = IntPtr.Zero; lock (_syncObject) { // Check if there is embedded thumbnail or not int hr = UnsafeNativeMethods.WICBitmapFrameDecode.GetThumbnail( _frameSource, out thumbnail ); if (hr != (int)WinCodecErrors.WINCODEC_ERR_CODECNOTHUMBNAIL) { HRESULT.Check(hr); } } _isThumbnailCached = true; if (thumbnail != IntPtr.Zero) { BitmapSourceSafeMILHandle thumbHandle = new BitmapSourceSafeMILHandle(thumbnail); SafeMILHandle unmanagedPalette = BitmapPalette.CreateInternalPalette(); BitmapPalette palette = null; int hr = UnsafeNativeMethods.WICBitmapSource.CopyPalette( thumbHandle, unmanagedPalette ); if (hr == HRESULT.S_OK) { palette = new BitmapPalette(unmanagedPalette); } _thumbnail = new UnmanagedBitmapWrapper( CreateCachedBitmap( null, thumbHandle, BitmapCreateOptions.PreservePixelFormat, _cacheOption, palette )); _thumbnail.Freeze(); } } }
static internal Imaging.BitmapPalette FromMILPaletteType(WICPaletteType type, bool hasAlpha) { int key = (int)type; Debug.Assert(key < c_maxPalettes); Imaging.BitmapPalette palette; Imaging.BitmapPalette[] palettes; if (hasAlpha) { palettes = transparentPalettes; } else { palettes = opaquePalettes; } palette = palettes[key]; if (palette == null) { lock (palettes) { // palettes might have changed while waiting for the lock. // Need to check again. palette = palettes[key]; if (palette == null) { palette = new Imaging.BitmapPalette(type, hasAlpha); palettes[key] = palette; } } } return palette; }
public static ImageData Create(ImageMetaData info, PixelFormat format, BitmapPalette palette, byte[] pixel_data) { return Create(info, format, palette, pixel_data, (int)info.Width * ((format.BitsPerPixel + 7) / 8)); }
public FormatConvertedBitmap(BitmapSource source, System.Windows.Media.PixelFormat destinationFormat, BitmapPalette destinationPalette, double alphaThreshold) { }
private void InitFromMemoryPtr( int pixelWidth, int pixelHeight, double dpiX, double dpiY, PixelFormat pixelFormat, BitmapPalette palette, IntPtr buffer, int bufferSize, int stride ) { if (pixelFormat.Palettized == true && palette == null) { throw new InvalidOperationException(SR.Get(SRID.Image_IndexedPixelFormatRequiresPalette)); } if (pixelFormat.Format == PixelFormatEnum.Default && pixelFormat.Guid == WICPixelFormatGUIDs.WICPixelFormatDontCare) { throw new System.ArgumentException( SR.Get(SRID.Effect_PixelFormat, pixelFormat), "pixelFormat" ); } _bitmapInit.BeginInit(); try { BitmapSourceSafeMILHandle wicBitmap; // Create the unmanaged resources Guid guidFmt = pixelFormat.Guid; using (FactoryMaker factoryMaker = new FactoryMaker()) { HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateBitmapFromMemory( factoryMaker.ImagingFactoryPtr, (uint)pixelWidth, (uint)pixelHeight, ref guidFmt, (uint)stride, (uint)bufferSize, buffer, out wicBitmap)); wicBitmap.CalculateSize(); } HRESULT.Check(UnsafeNativeMethods.WICBitmap.SetResolution( wicBitmap, dpiX, dpiY)); if (pixelFormat.Palettized) { HRESULT.Check(UnsafeNativeMethods.WICBitmap.SetPalette( wicBitmap, palette.InternalPalette)); } WicSourceHandle = wicBitmap; _isSourceCached = true; } catch { _bitmapInit.Reset(); throw; } _createOptions = BitmapCreateOptions.PreservePixelFormat; _cacheOption = BitmapCacheOption.OnLoad; _syncObject = WicSourceHandle; _bitmapInit.EndInit(); UpdateCachedSettings(); }
unsafe internal CachedBitmap( int pixelWidth, int pixelHeight, double dpiX, double dpiY, PixelFormat pixelFormat, BitmapPalette palette, System.Array pixels, int stride ) : base(true) // Use base class virtuals { if (pixels == null) { throw new System.ArgumentNullException("pixels"); } if (pixels.Rank != 1) { throw new ArgumentException(SR.Get(SRID.Collection_BadRank), "pixels"); } int elementSize = -1; if (pixels is byte[]) { elementSize = 1; } else if (pixels is short[] || pixels is ushort[]) { elementSize = 2; } else if (pixels is int[] || pixels is uint[] || pixels is float[]) { elementSize = 4; } else if (pixels is double[]) { elementSize = 8; } if (elementSize == -1) { throw new ArgumentException(SR.Get(SRID.Image_InvalidArrayForPixel)); } int destBufferSize = elementSize * pixels.Length; if (pixels is byte[]) { fixed(void *pixelArray = (byte[])pixels) InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (IntPtr)pixelArray, destBufferSize, stride); } else if (pixels is short[]) { fixed(void *pixelArray = (short[])pixels) InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (IntPtr)pixelArray, destBufferSize, stride); } else if (pixels is ushort[]) { fixed(void *pixelArray = (ushort[])pixels) InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (IntPtr)pixelArray, destBufferSize, stride); } else if (pixels is int[]) { fixed(void *pixelArray = (int[])pixels) InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (IntPtr)pixelArray, destBufferSize, stride); } else if (pixels is uint[]) { fixed(void *pixelArray = (uint[])pixels) InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (IntPtr)pixelArray, destBufferSize, stride); } else if (pixels is float[]) { fixed(void *pixelArray = (float[])pixels) InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (IntPtr)pixelArray, destBufferSize, stride); } else if (pixels is double[]) { fixed(void *pixelArray = (double[])pixels) InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (IntPtr)pixelArray, destBufferSize, stride); } }
public WriteableBitmap(int pixelWidth, int pixelHeight, double dpiX, double dpiY, System.Windows.Media.PixelFormat pixelFormat, BitmapPalette palette) { }
static internal BitmapPalette CreateFromBitmapSource(BitmapSource source) { Debug.Assert(source != null); SafeMILHandle bitmapSource = source.WicSourceHandle; Debug.Assert(bitmapSource != null && !bitmapSource.IsInvalid); SafeMILHandle unmanagedPalette = CreateInternalPalette(); BitmapPalette palette; // Don't throw on the HRESULT from this method. If it returns failure, // that likely means that the source doesn't have a palette. lock (source.SyncObject) { int hr = UnsafeNativeMethods.WICBitmapSource.CopyPalette( bitmapSource, unmanagedPalette); if (hr != HRESULT.S_OK) { return null; } } WICPaletteType paletteType; bool hasAlpha; HRESULT.Check(UnsafeNativeMethods.WICPalette.GetType(unmanagedPalette, out paletteType)); HRESULT.Check(UnsafeNativeMethods.WICPalette.HasAlpha(unmanagedPalette, out hasAlpha)); if (paletteType == WICPaletteType.WICPaletteTypeCustom || paletteType == WICPaletteType.WICPaletteTypeOptimal) { palette = new BitmapPalette(unmanagedPalette); } else { palette = BitmapPalettes.FromMILPaletteType(paletteType, hasAlpha); Debug.Assert(palette != null); } return palette; }
/// Returns if the Palette has any alpha within its colors internal static bool DoesPaletteHaveAlpha(BitmapPalette palette) { if (palette != null) { foreach (Color color in palette.Colors) { if (color.A != 255) { return true; } } } return false; }
public static BitmapSource Create(int pixelWidth, int pixelHeight, double dpiX, double dpiY, System.Windows.Media.PixelFormat pixelFormat, BitmapPalette palette, IntPtr buffer, int bufferSize, int stride) { return(default(BitmapSource)); }
public static ImageData Create(ImageMetaData info, PixelFormat format, BitmapPalette palette, byte[] pixel_data, int stride) { var bitmap = BitmapSource.Create((int)info.Width, (int)info.Height, DefaultDpiX, DefaultDpiY, format, palette, pixel_data, stride); bitmap.Freeze(); return new ImageData(bitmap, info); }
private void CreateAndShowMainWindow() { // Create the application's main window _mainWindow = new Window {Title = "BMP Imaging Sample"}; var mySv = new ScrollViewer(); var width = 128; var height = width; var stride = width/8; var pixels = new byte[height*stride]; // Try creating a new image with a custom palette. var colors = new List<Color> { Colors.Red, Colors.Blue, Colors.Green }; var myPalette = new BitmapPalette(colors); // Creates a new empty image with the pre-defined palette var image = BitmapSource.Create( width, height, 96, 96, PixelFormats.Indexed1, myPalette, pixels, stride); var stream = new FileStream("new.bmp", FileMode.Create); var encoder = new BmpBitmapEncoder(); var myTextBlock = new TextBlock {Text = "Codec Author is: " + encoder.CodecInfo.Author}; encoder.Frames.Add(BitmapFrame.Create(image)); encoder.Save(stream); // Open a Stream and decode a BMP image Stream imageStreamSource = new FileStream("tulipfarm.bmp", FileMode.Open, FileAccess.Read, FileShare.Read); var decoder = new BmpBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); BitmapSource bitmapSource = decoder.Frames[0]; // Draw the Image var myImage = new Image { Source = bitmapSource, Stretch = Stretch.None, Margin = new Thickness(20) }; // Open a Uri and decode a BMP image var myUri = new Uri("tulipfarm.bmp", UriKind.RelativeOrAbsolute); var decoder2 = new BmpBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); BitmapSource bitmapSource2 = decoder2.Frames[0]; // Draw the Image var myImage2 = new Image { Source = bitmapSource2, Stretch = Stretch.None, Margin = new Thickness(20) }; // Define a StackPanel to host the decoded BMP images var myStackPanel = new StackPanel { Orientation = Orientation.Vertical, VerticalAlignment = VerticalAlignment.Stretch, HorizontalAlignment = HorizontalAlignment.Stretch }; // Add the Image and TextBlock to the parent Grid myStackPanel.Children.Add(myImage); myStackPanel.Children.Add(myImage2); myStackPanel.Children.Add(myTextBlock); // Add the StackPanel as the Content of the Parent Window Object mySv.Content = myStackPanel; _mainWindow.Content = mySv; _mainWindow.Show(); }
public static ImageData CreateFlipped(ImageMetaData info, PixelFormat format, BitmapPalette palette, byte[] pixel_data, int stride) { var bitmap = BitmapSource.Create((int)info.Width, (int)info.Height, DefaultDpiX, DefaultDpiY, format, palette, pixel_data, stride); var flipped = new TransformedBitmap(bitmap, new ScaleTransform { ScaleY = -1 }); flipped.Freeze(); return new ImageData(flipped, info); }
public EriReader (Stream stream, EriMetaData info, Color[] palette, byte[] key_frame = null) { m_info = info; m_src_frame = key_frame; switch (m_info.Architecture) { case EriCode.Nemesis: case EriCode.RunlengthHuffman: case EriCode.RunlengthGamma: if (CvType.Lossless_ERI == m_info.Transformation && 0 == m_info.BlockingDegree) throw new InvalidFormatException(); break; case EriCode.ArithmeticCode: if (CvType.Lossless_ERI != m_info.Transformation) throw new InvalidFormatException(); break; default: throw new InvalidFormatException(); } switch (m_info.FormatType & EriType.Mask) { case EriType.RGB: if (m_info.BPP <= 8) m_nChannelCount = 1; else if (0 == (m_info.FormatType & EriType.WithAlpha)) m_nChannelCount = 3; else m_nChannelCount = 4; break; case EriType.Gray: m_nChannelCount = 1; break; default: throw new InvalidFormatException(); } if (CvType.Lossless_ERI == m_info.Transformation) InitializeLossless(); else if (CvType.LOT_ERI == m_info.Transformation || CvType.DCT_ERI == m_info.Transformation) InitializeLossy(); else throw new NotSupportedException ("Not supported ERI compression"); if (null != palette) Palette = new BitmapPalette (palette); CreateImageBuffer(); m_context.AttachInputFile (stream); m_pfnColorOperation = new PtrProcedure[0x10] { ColorOperation0000, ColorOperation0000, ColorOperation0000, ColorOperation0000, ColorOperation0000, ColorOperation0101, ColorOperation0110, ColorOperation0111, ColorOperation0000, ColorOperation1001, ColorOperation1010, ColorOperation1011, ColorOperation0000, ColorOperation1101, ColorOperation1110, ColorOperation1111 }; }