/// <summary> /// Заргуражет писели из картинки /// </summary> /// <param name="device">Устройство с помощью которого будет рисоваться эта картинка</param> /// <param name="filename">Путь к файлу с картинкой</param> /// <returns>Набор пикселей</returns> public static BitmapSource LoadBitmapSource(SharpDX.Direct3D11.DeviceContext device, string filename) { var pFormat = SharpDX.WIC.PixelFormat.Format32bppPRGBA; string ext = System.IO.Path.GetExtension(filename); if (ext.ToLower() == ".dds") { pFormat = SharpDX.WIC.PixelFormat.Format32bppRGBA; } using (var Imgfactory = new ImagingFactory2()) using (var d = new BitmapDecoder( Imgfactory, filename, DecodeOptions.CacheOnDemand )) using (var frame = d.GetFrame(0)) { var fconv = new FormatConverter(Imgfactory); fconv.Initialize( frame, pFormat, BitmapDitherType.None, null, 0.0, BitmapPaletteType.Custom); return(fconv); } }
/// <summary> /// Gets bitmap. /// </summary> /// <param name="image">The image.</param> /// <returns>Returns bitmap.</returns> private Bitmap GetBitmap(OxyImage image) { if (image == null) { return(null); } if (!this.imagesInUse.Contains(image)) { this.imagesInUse.Add(image); } Bitmap res; using (var stream = new MemoryStream(image.GetData())) { var decoder = new BitmapDecoder(this.wicFactory, stream, DecodeOptions.CacheOnDemand); var frame = decoder.GetFrame(0); var converter = new FormatConverter(this.wicFactory); converter.Initialize(frame, dx.WIC.PixelFormat.Format32bppPRGBA); res = Bitmap.FromWicBitmap(this.renderTarget, converter); } this.imageCache.Add(image, res); return(res); }
private static BitmapSource LoadBitmap(string filename, out bool IsSRgb) { var bitmapDecoder = new BitmapDecoder( Factory, filename, DecodeOptions.CacheOnDemand ); BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0); var metaReader = bitmapFrameDecode.MetadataQueryReader; if (metaReader == null) { IsSRgb = false; } else { var list = metaReader.QueryPaths; Dictionary <string, object> test = new Dictionary <string, object>(); foreach (var item in list) { test.Add(item, metaReader.GetMetadataByName(item)); } if (metaReader.TryGetMetadataByName("/sRGB/RenderingIntent", out object t).Success) { if ((ushort)t == 1) { IsSRgb = true; } } if (metaReader.TryGetMetadataByName("/app1/ifd/exif/{ushort=40961}", out t).Success) { if ((ushort)t == 1) { IsSRgb = true; } } IsSRgb = false; } if (IsSRgb) { System.Console.WriteLine(filename + " SRGB!"); } var formatConverter = new FormatConverter(Factory); formatConverter.Initialize( bitmapFrameDecode, PixelFormat.Format32bppPRGBA, BitmapDitherType.None, null, 0.0, BitmapPaletteType.Custom); return(formatConverter); }
public void convert_values_formats_the_value_using_the_format_string() { var converter = new FormatConverter(); converter.FormatString = "Value 1: {0} and value 2: {1}"; Assert.Equal("Value 1: 26 and value 2: 27", converter.Convert(new object[] { 26, 27 }, null, null, null)); }
private static BitmapSource LoadBitmap(Stream stream, out SharpDX.WIC.BitmapDecoder decoder) { if (imgfactory == null) { imgfactory = new ImagingFactory(); } decoder = new SharpDX.WIC.BitmapDecoder( imgfactory, stream, DecodeOptions.CacheOnDemand ); var fconv = new FormatConverter(imgfactory); using (var frame = decoder.GetFrame(0)) { fconv.Initialize( frame, PixelFormat.Format32bppRGBA, BitmapDitherType.None, null, 0.0, BitmapPaletteType.Custom); } return(fconv); }
public ImageLoader() { alphaThresholdPct = 0.0; factory = new ImagingFactory2(); fmtConverter = new FormatConverter(factory); }
private static SharpDX.Direct2D1.Bitmap LoadBitmapFromContentFile(ImagingFactory2 imagingFactory, string filePath, RenderTarget renderTarget) { SharpDX.Direct2D1.Bitmap newBitmap; // Neccessary for creating WIC objects. //NativeFileStream fileStream = new NativeFileStream(filePath, // NativeFileMode.Open, NativeFileAccess.Read); // Used to read the image source file. BitmapDecoder bitmapDecoder = new BitmapDecoder(imagingFactory, filePath, DecodeOptions.CacheOnDemand); // Get the first frame of the image. BitmapFrameDecode frame = bitmapDecoder.GetFrame(0); // Convert it to a compatible pixel format. FormatConverter converter = new FormatConverter(imagingFactory); converter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA); // Create the new Bitmap1 directly from the FormatConverter. newBitmap = SharpDX.Direct2D1.Bitmap1.FromWicBitmap(renderTarget, converter); //Utilities.Dispose(ref bitmapDecoder); //Utilities.Dispose(ref fileStream); //Utilities.Dispose(ref imagingFactory); return(newBitmap); }
private DataSet GetDataSourceForDynamicExportDemo() { DataSet dataSource = new DataSet(); // 标题表 DataTable 标题表 = new DataTable("标题表"); 标题表.Columns.Add("标题"); 标题表.Columns.Add("副标题"); DataRow dr = 标题表.NewRow(); dr["标题"] = "动态报表" + typeof(DynamicExcelDataViewModel).Name; dr["副标题"] = "动态模版:" + typeof(ExcelDataViewModel).Name; 标题表.Rows.Add(dr); dataSource.Tables.Add(标题表); // 数据表 using (ExcelReader excelReader = new ExcelReader(SysContext.Config.ReportTemplateDirectory_Physical + "测试模板.xlsx", "哈哈", true)) { List <DynamicExcelDataViewModel> modelList = excelReader.Read <DynamicExcelDataViewModel>(); DataTable 数据表 = FormatConverter.ListToDataTable <DynamicExcelDataViewModel>(modelList, (p => p.GetCustomAttributes(typeof(DisplayNameAttribute), true).Length > 0)); 数据表.TableName = "数据表"; dataSource.Tables.Add(数据表); } return(dataSource); }
/// <summary> /// Gets a Direct2D bitmap to use on the specified render target. /// </summary> /// <param name="renderTarget">The render target.</param> /// <returns>The Direct2D bitmap.</returns> public override OptionalDispose <D2DBitmap> GetDirect2DBitmap(SharpDX.Direct2D1.RenderTarget renderTarget) { FormatConverter converter = new FormatConverter(Direct2D1Platform.ImagingFactory); converter.Initialize(WicImpl, SharpDX.WIC.PixelFormat.Format32bppPBGRA); return(new OptionalDispose <D2DBitmap>(D2DBitmap.FromWicBitmap(renderTarget, converter), true)); }
public bool LoadFromStream(string textureKey, Stream stream) { try { if (this.textureCache.ContainsKey(textureKey)) { return(true); } using (var bitmapDecoder = new BitmapDecoder(this.imagingFactory, stream, DecodeOptions.CacheOnDemand)) { var frame = bitmapDecoder.GetFrame(0); using (var converter = new FormatConverter(this.imagingFactory)) { converter.Initialize(frame, PixelFormat.Format32bppPRGBA); // Format32bppPRGBA var bitmap = Bitmap.FromWicBitmap(this.renderContext.RenderTarget, converter); this.textureCache[textureKey] = new D3D11Texture(bitmap); } } return(true); } catch (Exception e) { Log.Error(e); return(false); } }
public static Bitmap Decode(RenderTarget device, BitmapDecoder decoder) { var frame = decoder.GetFrame(0); var converter = new FormatConverter(Image.ImageFactory); foreach (var format in _pixelFormatEnumerator) { try { converter.Initialize(frame, format); var bmp = Bitmap.FromWicBitmap(device, converter); TryCatch(() => converter.Dispose()); TryCatch(() => frame.Dispose()); return(bmp); } catch { TryCatch(() => converter.Dispose()); converter = new FormatConverter(Image.ImageFactory); } } TryCatch(() => converter.Dispose()); TryCatch(() => frame.Dispose()); throw new Exception("Unsupported Image Format!"); }
void ColorCameraLoop() { while (true) { var encodedColorData = camera.Client.LatestJPEGImage(); // decode JPEG var memoryStream = new MemoryStream(encodedColorData); var stream = new WICStream(imagingFactory, memoryStream); // decodes to 24 bit BGR var decoder = new SharpDX.WIC.BitmapDecoder(imagingFactory, stream, SharpDX.WIC.DecodeOptions.CacheOnLoad); var bitmapFrameDecode = decoder.GetFrame(0); // convert to 32 bpp var formatConverter = new FormatConverter(imagingFactory); formatConverter.Initialize(bitmapFrameDecode, SharpDX.WIC.PixelFormat.Format32bppBGR); formatConverter.CopyPixels(nextColorData, Kinect2Calibration.colorImageWidth * 4); // TODO: consider copying directly to texture native memory //lock (colorData) // Swap<byte[]>(ref colorData, ref nextColorData); lock (renderLock) // necessary? { UpdateColorImage(device.ImmediateContext, nextColorData); } memoryStream.Close(); memoryStream.Dispose(); stream.Dispose(); decoder.Dispose(); formatConverter.Dispose(); bitmapFrameDecode.Dispose(); } }
public static Bitmap LoadPngFromStream(Stream stream) { // Read input var wicStream = new WICStream(DXGraphicsService.FactoryImaging, stream); var decoder = new PngBitmapDecoder(DXGraphicsService.FactoryImaging); decoder.Initialize(wicStream, DecodeOptions.CacheOnDemand); var bitmapFrameDecode = decoder.GetFrame(0); var width = bitmapFrameDecode.Size.Width; var height = bitmapFrameDecode.Size.Height; //Convert WIC pixel format to D2D1 format var formatConverter = new FormatConverter(DXGraphicsService.FactoryImaging); formatConverter.Initialize(bitmapFrameDecode, PixelFormat.Format32bppBGRA, BitmapDitherType.None, null, 0f, BitmapPaletteType.MedianCut); // Bitmaps and render target settings var wicBitmap = new Bitmap( DXGraphicsService.FactoryImaging, width, height, PixelFormat.Format32bppBGRA, BitmapCreateCacheOption.CacheOnLoad); bitmapFrameDecode.Dispose(); decoder.Dispose(); wicStream.Dispose(); return(wicBitmap); }
/// <summary> /// 創建縮略圖 /// </summary> /// <typeparam name="T">IFileUploadResult</typeparam> /// <param name="pResults">文件集合</param> /// <param name="serverRPath">服務器存放相對路徑</param> /// <param name="thumbHeadName">縮略圖頭名稱</param> protected void ConvertAndCreateThumb <T>(List <T> pResults, string serverRPath, string thumbHeadName) where T : IFileUploadResult, new() { string strThumbFileName = string.Empty; string serverAPath = serverRPath.Replace("/", @"\"); //轉換操作 FormatConverter pCon = new FormatConverter(); foreach (T pT in pResults) { // 25487815728572_stb.mp4 strThumbFileName = string.Format("{0}{1}", pT.FileName, thumbHeadName); // string err = pCon.Convert(pT.APath, serverAPath, strThumbFileName, FormatConverter.VideoType.MP4, true, true); if (!string.IsNullOrEmpty(err)) { EGExceptionOperator.ThrowX <Exception>(err, EGActionCode.文件上传失败); } else { pT.APath = pT.APath.Replace(pT.FileName, strThumbFileName); pT.FileName = strThumbFileName; pT.RPath = string.Format("{0}/{1}.{2}", serverRPath, strThumbFileName, pT.FormatName); pT.RPathThumb = string.Format("{0}/{1}.{2}", serverRPath, strThumbFileName, "jpg"); } } }
private Bitmap CreateBitmap(string path) { var renderTarget = renderTargetProvider.RenderTarget; var imagingFactory = imagingFactoryProvider.ImagingFactory; if (renderTarget == null || renderTarget.IsDisposed || imagingFactory == null || imagingFactory.IsDisposed) { return(null); // TODO: throw exception } var fileStream = new NativeFileStream(path, NativeFileMode.Open, NativeFileAccess.Read); var bitmapDecoder = new BitmapDecoder(imagingFactory, fileStream, DecodeOptions.CacheOnDemand); var frame = bitmapDecoder.GetFrame(0); var converter = new FormatConverter(imagingFactory); converter.Initialize(frame, PixelFormat.Format32bppPRGBA); var bitmap = Bitmap.FromWicBitmap(renderTarget, converter); Utilities.Dispose(ref bitmapDecoder); Utilities.Dispose(ref fileStream); return(bitmap); }
public BitmapFrameDecoder(Func <Device, int, int, int, Format, Usage, Texture> textureFactory, MemoryPool memoryPool, Stream stream) : base(textureFactory, memoryPool) { var dataStream = stream as SharpDX.DataStream; using (var wicStream = new WICStream(Factory, new SharpDX.DataPointer(dataStream.DataPointer, (int)dataStream.Length))) using (var decoder = new BitmapDecoder(Factory, wicStream, DecodeOptions.CacheOnLoad)) { using (var frame = decoder.GetFrame(0)) { var dstPixelFormat = PixelFormat.Format32bppBGRA; Width = frame.Size.Width; Height = frame.Size.Height; FStride = PixelFormat.GetStride(dstPixelFormat, Width); FLength = FStride * Height; FBuffer = memoryPool.UnmanagedPool.GetMemory(FLength); if (frame.PixelFormat != dstPixelFormat) { using (var converter = new FormatConverter(Factory)) { converter.Initialize(frame, dstPixelFormat); converter.CopyPixels(FStride, FBuffer); } } else { frame.CopyPixels(FStride, FBuffer); } } } memoryPool.StreamPool.PutStream(stream); }
private static BitmapSource LoadBitmap(string filename) { Imgfactory = new ImagingFactory(); var d = new BitmapDecoder( Imgfactory, filename, DecodeOptions.CacheOnDemand ); // var frame = d.GetFrame(0); var fconv = new FormatConverter(Imgfactory); fconv.Initialize(frame, PixelFormat.Format32bppPRGBA, BitmapDitherType.None, null, 0.0, BitmapPaletteType.Custom); d.Dispose(); frame.Dispose(); //fconv.Dispose(); Imgfactory.Dispose(); //MessageBox.Show("Pause"); return(fconv); //return null; }
public void convert_value_throws_if_format_string_is_null() { var converter = new FormatConverter(); var ex = Assert.Throws <InvalidOperationException>(() => converter.Convert(27, null, null, null)); Assert.Equal("No FormatString has been specified.", ex.Message); }
/// <summary> /// Loads an existing image file into a SharpDX.Direct2D1.Bitmap1. /// </summary> /// <param name="filePath">Relative path to the content file.</param> /// <returns>Loaded bitmap.</returns> private SharpDX.Direct2D1.Bitmap1 LoadBitmapFromContentFile(string filePath) { SharpDX.Direct2D1.Bitmap1 newBitmap; // Neccessary for creating WIC objects. ImagingFactory imagingFactory = new ImagingFactory(); NativeFileStream fileStream = new NativeFileStream(Package.Current.InstalledLocation.Path + filePath, NativeFileMode.Open, NativeFileAccess.Read); // Used to read the image source file. BitmapDecoder bitmapDecoder = new BitmapDecoder(imagingFactory, fileStream, DecodeOptions.CacheOnDemand); // Get the first frame of the image. BitmapFrameDecode frame = bitmapDecoder.GetFrame(0); // Convert it to a compatible pixel format. FormatConverter converter = new FormatConverter(imagingFactory); converter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA); // Create the new Bitmap1 directly from the FormatConverter. newBitmap = SharpDX.Direct2D1.Bitmap1.FromWicBitmap(d2dContext, converter); Utilities.Dispose(ref bitmapDecoder); Utilities.Dispose(ref fileStream); Utilities.Dispose(ref imagingFactory); Utilities.Dispose(ref converter); Utilities.Dispose(ref frame); return(newBitmap); }
public void convert_values_uses_the_specified_culture() { var converter = new FormatConverter(); converter.FormatString = "Value 1: {0:00.00} and value 2: {1:00.00}"; Assert.Equal("Value 1: 26,00 and value 2: 27,00", converter.Convert(new object[] { 26, 27 }, null, null, new CultureInfo("de-DE"))); }
private void Assert(string markdown, string expectedHtml) { var converter = new FormatConverter<HtmlData>( new MarkdownDataBuilder(markdown), new PlainToHtmlConverter()); var actual = converter.Convert().Content; NUnit.Framework.Assert.AreEqual(expectedHtml, actual); }
/// <summary> /// Gets a Direct2D bitmap to use on the specified render target. /// </summary> /// <param name="renderTarget">The render target.</param> /// <returns>The Direct2D bitmap.</returns> public override SharpDX.Direct2D1.Bitmap GetDirect2DBitmap(SharpDX.Direct2D1.RenderTarget renderTarget) { FormatConverter converter = new FormatConverter(_factory); converter.Initialize(WicImpl, SharpDX.WIC.PixelFormat.Format32bppPBGRA); return(SharpDX.Direct2D1.Bitmap.FromWicBitmap(renderTarget, converter)); }
/// <summary> /// Called when a game resource is loaded. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="Platformer.Engine.Resources.ResourceLoadEventArgs" /> instance containing the event data.</param> protected override void OnGameResourceLoaded(Object sender, ResourceLoadEventArgs e) { if (e.ResourceType == typeof(Map)) { var map = e.LoadedResource as Map; foreach (var tileSet in map.TileSets) { using (var decoder = new BitmapDecoder(_imagingFactory, tileSet.ImagePath, DecodeOptions.CacheOnDemand)) { using (var formatConverter = new FormatConverter(_imagingFactory)) { formatConverter.Initialize( decoder.GetFrame(0), PixelFormat.Format32bppPBGRA, BitmapDitherType.DualSpiral8x8, null, 0.0, BitmapPaletteType.Custom); var bitmap = SharpDX.Direct2D1.Bitmap1.FromWicBitmap(_d2dContext, formatConverter); _tileSetTextures.Add(tileSet.Id, bitmap); } } } } }
//Save to cometrade #region private static string FileParamLineData(ushort[] paramLine, int lineNum) { string str1; int i; ulong ulTemp; _count64 = 0; _count32 = 0; _count16 = 0; string str = (lineNum + 1) + ","; for (i = 0; i < ScopeConfig.ChannelCount; i++) { if (ScopeConfig.ChannelType[i] == 0) { ulTemp = ParseArr(i, paramLine); str1 = FormatConverter.GetValue(ulTemp, (byte)ScopeConfig.OscilFormat[i]); str1 = str1.Replace(",", "."); str = str + "," + str1; } } for (i = 0; i < ScopeConfig.ChannelCount; i++) { if (ScopeConfig.ChannelType[i] == 1) { ulTemp = ParseArr(i, paramLine); str1 = FormatConverter.GetValue(ulTemp, (byte)ScopeConfig.OscilFormat[i]); str1 = str1.Replace(",", "."); str = str + "," + str1; } } return(str); }
/// <summary> /// Example of using AsposeFormatConverter /// </summary> /// <param name="args"></param> static void Main(string[] args) { _converter = new FormatConverter(); _availableFormats = _converter.GetSupportedConversionFormats(); // Create file names var xmlFileName = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + "Test.xml"; var binFileName = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + "Test.bin"; var xmlConvertFileName = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + "ConvertTest.xml"; var binConvertFileName = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + "ConvertTest.bin"; // Create Demo Files CreateNewXml(xmlFileName); CreateNewBin(binFileName); // Convert Demo var dataEntity = OpenAnyFormat(xmlFileName); ConvertEntityTo(dataEntity, binConvertFileName, _availableFormats.FirstOrDefault(it => it.GetName() == "Bin")); dataEntity = OpenAnyFormat(binFileName); ConvertEntityTo(dataEntity, xmlConvertFileName, _availableFormats.FirstOrDefault(it => it.GetName() == "Xml")); WriteReport(xmlFileName, binFileName, binConvertFileName, xmlConvertFileName); Console.ReadKey(); }
public ShaderResourceView LoadBitmapShaderResource(System.Drawing.Bitmap btm) { ShaderResourceView res = null; try { var ms = new MemoryStream(); btm.Save(ms, System.Drawing.Imaging.ImageFormat.Png); ms.Position = 0; var factory = new SharpDX.WIC.ImagingFactory(); var bitmapDecoder = new BitmapDecoder(factory, ms, DecodeOptions.CacheOnDemand); var result = new FormatConverter(factory); result.Initialize(bitmapDecoder.GetFrame(0), PixelFormat.Format32bppPRGBA, BitmapDitherType.None, null, 0.0, BitmapPaletteType.Custom); using (var texture = CreateTexture2DFromBitmap(device, result)) { var srvDesc = new ShaderResourceViewDescription() { Format = texture.Description.Format, Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D, }; srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.Texture2D.MipLevels = -1; res = new ShaderResourceView(device, texture, srvDesc); device.ImmediateContext.GenerateMips(res); } // TextureResource = ShaderResourceView.FromFile(device, fileName); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine($"TexturedLoader {ex.Message}"); } return(res); }
static void Main(string[] args) { // convert xml string to json string string personJson = FormatConverter.XmlToJsonAsString(xmlString); Console.WriteLine("{0}\n", personJson); // convert xml string to JObject JObject jobj = FormatConverter.XmlToJsonAsJObject(xmlString); Console.WriteLine(jobj); // convert json string to XmlDocument XmlDocument personXml = FormatConverter.JsonToXml(personJson); PrintXML(personXml); // convert xml document to json string json = FormatConverter.XmlToJsonAsString(personXml); Console.WriteLine("\n{0}\n", json); // convert JObject to Xml Document XmlDocument result = FormatConverter.JsonToXml(jobj); PrintXML(result); }
static byte[] CreateRaw(IntPtr pixels, int width, int height) { using (var bitmap = new System.Drawing.Bitmap(width, height, width * 4, System.Drawing.Imaging.PixelFormat.Format32bppArgb, pixels)) { using (var stream = new MemoryStream()) { bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp); var factory = new ImagingFactory2(); using (var decoder = new BitmapDecoder(factory, stream, DecodeOptions.CacheOnDemand)) { using (var formatConverter = new FormatConverter(factory)) { formatConverter.Initialize(decoder.GetFrame(0), PixelFormat.Format32bppPRGBA); var stride = formatConverter.Size.Width * 4; using (var dataStream = new SharpDX.DataStream(formatConverter.Size.Height * stride, true, true)) { formatConverter.CopyPixels(stride, dataStream); byte[] b; using (BinaryReader br = new BinaryReader(dataStream)) { b = br.ReadBytes((int)dataStream.Length); } return(b); } } } } } }
private static Bitmap LoadBitmapFromMemory(RenderTarget device, byte[] bytes) { if (device == null) { throw new ArgumentNullException(nameof(device)); } if (bytes == null) { throw new ArgumentNullException(nameof(bytes)); } if (bytes.Length == 0) { throw new ArgumentOutOfRangeException(nameof(bytes)); } Bitmap bmp = null; MemoryStream stream = null; BitmapDecoder decoder = null; BitmapFrameDecode frame = null; FormatConverter converter = null; try { stream = new MemoryStream(bytes); decoder = new BitmapDecoder(ImageFactory, stream, DecodeOptions.CacheOnDemand); bmp = ImageDecoder.Decode(device, decoder); decoder.Dispose(); stream.Dispose(); return(bmp); } catch { if (converter?.IsDisposed == false) { converter.Dispose(); } if (frame?.IsDisposed == false) { frame.Dispose(); } if (decoder?.IsDisposed == false) { decoder.Dispose(); } if (stream != null) { TryCatch(() => stream.Dispose()); } if (bmp?.IsDisposed == false) { bmp.Dispose(); } throw; } }
//------------------------------------------------------------------------------------- // Encodes a single frame //------------------------------------------------------------------------------------- private static void EncodeImage(PixelBuffer image, WICFlags flags, BitmapFrameEncode frame) { Guid pfGuid; if (!ToWIC(image.Format, out pfGuid)) { throw new NotSupportedException("Format not supported"); } frame.Initialize(); frame.SetSize(image.Width, image.Height); frame.SetResolution(72, 72); Guid targetGuid = pfGuid; frame.SetPixelFormat(ref targetGuid); if (targetGuid != pfGuid) { using (var source = new Bitmap(Factory, image.Width, image.Height, pfGuid, new DataRectangle(image.DataPointer, image.RowStride), image.BufferStride)) { using (var converter = new FormatConverter(Factory)) { using (var palette = new Palette(Factory)) { palette.Initialize(source, 256, true); converter.Initialize(source, targetGuid, GetWICDither(flags), palette, 0, BitmapPaletteType.Custom); int bpp = GetBitsPerPixel(targetGuid); if (bpp == 0) { throw new NotSupportedException("Unable to determine the Bpp for the target format"); } int rowPitch = (image.Width * bpp + 7) / 8; int slicePitch = rowPitch * image.Height; var temp = Utilities.AllocateMemory(slicePitch); try { converter.CopyPixels(rowPitch, temp, slicePitch); frame.Palette = palette; frame.WritePixels(image.Height, temp, rowPitch, slicePitch); } finally { Utilities.FreeMemory(temp); } } } } } else { // No conversion required frame.WritePixels(image.Height, image.DataPointer, image.RowStride, image.BufferStride); } frame.Commit(); }
public void ctor_that_takes_format_string_assigns_to_format_string() { var converter = new FormatConverter(null); Assert.Null(converter.FormatString); converter = new FormatConverter("abc"); Assert.Equal("abc", converter.FormatString); }
public void convert_value_formats_the_value_using_the_format_string() { var converter = new FormatConverter { FormatString = "{0:00.00}" }; Assert.Equal("01.00", converter.Convert(1d, null, null, null)); }
public static void WarekiToSeirekiTest(string wareki, string warekiPattern) { object output; output = FormatConverter.WarekiToSeireki(wareki, warekiPattern); Assert.IsInstanceOf(typeof(DateTime), output); }
public void convert_back_value_returns_unset_value_if_the_conversion_fails() { var converter = new FormatConverter { FormatString = "{0:00.00}" }; Assert.Same(DependencyProperty.UnsetValue, converter.ConvertBack("abc", typeof(int), null, null)); }
public void convert_value_uses_the_specified_culture() { var converter = new FormatConverter { FormatString = "{0:00.00}" }; Assert.Equal("01,00", converter.Convert(1d, null, null, new CultureInfo("de-DE"))); }
public void convert_back_value_converts_to_target_type_if_possible() { var converter = new FormatConverter { FormatString = "{0:00.00}" }; Assert.Equal(123, converter.ConvertBack("123", typeof(int), null, null)); Assert.Equal(13.80, converter.ConvertBack("13.8", typeof(double), null, null)); }
static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("Usage: Homework.exe <filename>"); return; } var fileName = args[0]; var rawData = File.ReadAllText(fileName); var converter = new FormatConverter<HtmlData>( new MarkdownDataBuilder(rawData), new PlainToHtmlConverter()); File.WriteAllText(BuildHtmlFileName(fileName), converter.Convert().Content); }
public void ctor_format_string_is_null_by_default() { var converter = new FormatConverter(); Assert.Null(converter.FormatString); }
public void convert_back_values_returns_null() { var converter = new FormatConverter(); Assert.Null(converter.ConvertBack("something", new Type[] { }, null, null)); }
/// <summary> /// Gets bitmap. /// </summary> /// <param name="image">The image.</param> /// <returns>Returns bitmap.</returns> private Bitmap GetBitmap(OxyImage image) { if (image == null) { return null; } if (!this.imagesInUse.Contains(image)) { this.imagesInUse.Add(image); } Bitmap res; using (var stream = new MemoryStream(image.GetData())) { var decoder = new BitmapDecoder(this.wicFactory, stream, DecodeOptions.CacheOnDemand); var frame = decoder.GetFrame(0); var converter = new FormatConverter(this.wicFactory); converter.Initialize(frame, dx.WIC.PixelFormat.Format32bppPRGBA); res = Bitmap.FromWicBitmap(this.renderTarget, converter); } this.imageCache.Add(image, res); return res; }
public void convert_back_value_throws_if_there_is_no_target_type() { var converter = new FormatConverter(); Assert.Throws<ArgumentNullException>(() => converter.ConvertBack(null, (Type)null, null, null)); }
public void convert_back_value_uses_specified_culture() { var converter = new FormatConverter { FormatString = "{0:00.00}" }; Assert.Equal(123, converter.ConvertBack("123", typeof(int), null, new CultureInfo("de-DE"))); Assert.Equal(13.80, converter.ConvertBack("13,8", typeof(double), null, new CultureInfo("de-DE"))); }
public void convert_values_throws_if_format_string_is_null() { var converter = new FormatConverter(); var ex = Assert.Throws<InvalidOperationException>(() => converter.Convert(new object[] { 26, 27 }, null, null, null)); Assert.Equal("No FormatString has been specified.", ex.Message); }