public static ImageDescriptor DecodeBitmapImage(ref string filePath, int decodePixelWidth) { ImageDescriptor result = null; try { Bitmap bmp; using (var fileStream = new FileStream( filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 10240, FileOptions.SequentialScan)) { var bf = BitmapFrame.Create( fileStream, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnLoad); result = new ImageDescriptor(null, bf.Decoder.CodecInfo.FriendlyName, filePath); var icon = Utility.GenerateHICON( bf, new Size(decodePixelWidth, Convert.ToSingle(bf.PixelHeight) / bf.PixelWidth * decodePixelWidth)); bmp = Util.BitmapSourceToBitmap(icon); bf = null; icon = null; } if (bmp != null) { result.BitmapSource = Util.BitmapToBitmapImage(ref bmp, BitmapCacheOption.OnLoad, BitmapCreateOptions.DelayCreation); bmp.Dispose(); } } catch (Exception excptn) { while (excptn != null) { Debug.WriteLine(excptn.Message); excptn = excptn.InnerException; } } return result; }
/// <summary> /// Find the Amazon machine image identified by the ImageDescriptor /// </summary> /// <param name="ec2Client">The EC2 client used to search for the image.</param> /// <param name="descriptor">The descriptor used to identify the image.</param> /// <returns>The Amazon machine image.</returns> public static Image FindImage(AmazonEC2 ec2Client, ImageDescriptor descriptor) { if (ec2Client == null) throw new ArgumentNullException("ec2Client"); if (descriptor == null) throw new ArgumentNullException("descriptor"); var result = ec2Client.DescribeImages(new DescribeImagesRequest() { Owner = new List<string>() { "amazon" }, Filter = new List<Filter>() { new Filter(){Name = "name", Value = new List<string>(){descriptor.NamePrefix}} } }).DescribeImagesResult; if (result.Image.Count == 0) return null; var image = result.Image.OrderByDescending(x => x.Name).First(); return image; }
public CameraThumbnailProducedEventArgs(CameraSummary summary, Bitmap thumbnail, ImageDescriptor imageDescriptor, bool hadError, bool cancelled) { this.Summary = summary; this.Thumbnail = thumbnail; this.ImageDescriptor = imageDescriptor; this.HadError = hadError; this.Cancelled = cancelled; }
public static MarkerOptions CreateTexture2DMarkerOptions(Texture2D tex) { var london = new LatLng(BerlinLatitude, BerlinLongitude); return(NewMarkerOptions(london, ImageDescriptor.FromTexture2D(tex))); }
private bool NeedsReallocation(ImageDescriptor imageDescriptor, long availableMemory) { return(!allocated || this.imageDescriptor != imageDescriptor || this.availableMemory != availableMemory); }
/// <summary> /// Find the Amazon machine image identified by the ImageDescriptor. /// </summary> /// <param name="ec2Client">The EC2 client used to search for the image.</param> /// <param name="descriptor">The descriptor used to identify the image.</param> /// <returns>The Amazon machine image.</returns> public static Image FindImage(IAmazonEC2 ec2Client, ImageDescriptor descriptor) { if (ec2Client == null) throw new ArgumentNullException("ec2Client"); if (descriptor == null) throw new ArgumentNullException("descriptor"); int retryCount = 1; Image image = null; do { var result = ec2Client.DescribeImages(new DescribeImagesRequest() { Owners = new List<string>() { "amazon" }, Filters = new List<Filter>() { new Filter(){Name = "name", Values = new List<string>(){descriptor.NamePrefix}} } }); if (result.Images.Count != 0) image = result.Images.OrderByDescending(x => x.Name).First(); else { // backing control file may be outdated, reload and try once more if (retryCount == 1) { LOGGER.InfoFormat("FindImage - DescribeImages call for image descriptor '{0}' (name prefix '{1}') yielded no results, assuming outdated control file and reloading", descriptor.DefinitionKey, descriptor.NamePrefix); LoadDefinitionsFromWeb(); } retryCount++; } } while (image == null && retryCount <= 2); if (image == null) LOGGER.InfoFormat("FindImage - failed to find valid AMI image for descriptor '{0}' (name prefix '{1}')", descriptor.DefinitionKey, descriptor.NamePrefix); return image; }
private static DescribeImagesRequest CreateDescribeImagesRequest(ImageDescriptor descriptor) { return new DescribeImagesRequest() { Owners = new List<string>() { "amazon" }, Filters = new List<Filter>() { new Filter(){Name = "name", Values = new List<string>(){descriptor.NamePrefix}} } }; }
/// <summary> /// Attempt to preallocate the circular buffer for as many images as possible that fits in available memory. /// </summary> public bool AllocateBuffers(ImageDescriptor imageDescriptor, long availableMemory) { if (!NeedsReallocation(imageDescriptor, availableMemory)) { return(true); } int targetCapacity = (int)(availableMemory / imageDescriptor.BufferSize); bool memoryPressure = minCapacity * imageDescriptor.BufferSize > availableMemory; if (memoryPressure) { // The user explicitly asked to not use enough memory. We try to honor the request by lowering the min levels. // This may result in thread cross talks. reserveCapacity = Math.Max(targetCapacity, 2); minCapacity = Math.Max(targetCapacity + 1, 3); targetCapacity = Math.Max(targetCapacity, minCapacity); } else { reserveCapacity = 8; minCapacity = 12; targetCapacity = Math.Max(targetCapacity, minCapacity); } bool compatible = ImageDescriptor.Compatible(this.imageDescriptor, imageDescriptor); if (compatible && targetCapacity <= fullCapacity) { FreeSome(targetCapacity); this.fullCapacity = frames.Count; this.availableMemory = availableMemory; return(true); } if (!compatible) { FreeAll(); } stopwatch.Restart(); frames.Capacity = targetCapacity; log.DebugFormat("Allocating {0} frames.", targetCapacity - fullCapacity); int bufferSize = ImageFormatHelper.ComputeBufferSize(imageDescriptor.Width, imageDescriptor.Height, imageDescriptor.Format); try { for (int i = fullCapacity; i < targetCapacity; i++) { Frame slot = new Frame(bufferSize); frames.Add(slot); } } catch (Exception e) { log.ErrorFormat("Error while allocating delay buffer."); log.Error(e); } if (frames.Count > 0) { // The following variables are used during frame -> bitmap conversion. this.rect = new Rectangle(0, 0, imageDescriptor.Width, imageDescriptor.Height); this.pitch = imageDescriptor.Width * 3; this.tempJpeg = new byte[bufferSize]; this.allocated = true; this.fullCapacity = frames.Count; this.availableMemory = availableMemory; this.imageDescriptor = imageDescriptor; // Better do the GC now to push everything to gen2 and LOH rather than taking a hit later during normal streaming operations. GC.Collect(2); } log.DebugFormat("Allocated delay buffer: {0} ms. Total: {1} frames.", stopwatch.ElapsedMilliseconds, fullCapacity); return(allocated); }
private bool NeedsReallocation(ImageDescriptor imageDescriptor) { return(!allocated || this.imageDescriptor != imageDescriptor); }
/// <summary> /// In case of configure failure, we would have retrieved a single image and the corresponding image descriptor. /// A limitation of the single snapshot retriever is that the format is always RGB24, even though the grabber may /// use a different format. /// </summary> public ImageDescriptor GetPrepareFailedImageDescriptor(ImageDescriptor input) { return(input); }
public static int GetPitch(GalImageFormat Format, int Width) { ImageDescriptor Desc = GetImageDescriptor(Format); return(Desc.BytesPerPixel * DivRoundUp(Width, Desc.BlockWidth)); }
/// <summary> /// Creates a new instance with the given values. All values can be NULL except of /// <paramref name="text"/>. Note, no infotip is applied. /// </summary> /// <param name="text">Text of the item. Must not be NULL or empty!</param> /// <param name="image">Image of the item</param> public ContentAssistItem(string text, ImageDescriptor image) : this(text, image, null, null) { // Nothing to do here }
private static GifFrame DecodeFrame(GraphicControlExtension extension, ImageDescriptor descriptor, TableBasedImageData data, bool filled, int width, int height, Color32[] state, Color32[] colorTable) { var colorIndexes = LzwDecoder.Decode(data.ImageData, data.LzwMinimumCodeSize); return(DecodeFrame(extension, descriptor, colorIndexes, filled, width, height, state, colorTable)); }
/// <summary> /// Iterator can be used for large GIF-files in order to display progress bar. /// </summary> public IEnumerable <List <byte> > EncodeIterator(int scale = 1) { if (_free) { if (Frames[0].Texture.width > 256 || Frames[0].Texture.height > 256) { throw new Exception("The free version has maximum supported size 256x256 px. Please consider buying the Full version of Power GIF."); } if (Frames.Count > 20) { throw new Exception("The Free version is limited by 20 frames. Please consider buying the Full version of Power GIF."); } } const string header = "GIF89a"; var width = (ushort)(Frames[0].Texture.width * scale); var height = (ushort)(Frames[0].Texture.height * scale); var globalColorTable = new List <Color32>(); var applicationExtension = new ApplicationExtension(); var bytes = new List <byte>(); var colorTables = new List <Color32> [Frames.Count]; var distinctColors = new Dictionary <int, List <Color32> >(); var manualResetEvent = new ManualResetEvent(false); for (var i = 0; i < Frames.Count; i++) { var frame = Frames[i]; ThreadPool.QueueUserWorkItem(context => { var distinct = frame.Texture.GetPixels32().Distinct().ToList(); lock (distinctColors) { distinctColors.Add((int)context, distinct); if (distinctColors.Count == Frames.Count) { manualResetEvent.Set(); } } }, i); } manualResetEvent.WaitOne(); for (var i = 0; i < Frames.Count; i++) { var colors = distinctColors[i]; var add = colors.Where(j => !globalColorTable.Contains(j)).ToList(); if (globalColorTable.Count + add.Count <= 256) { globalColorTable.AddRange(add); colorTables[i] = globalColorTable; } else if (add.Count <= 256) // Introducing local color table { colorTables[i] = colors; } else { throw new Exception($"Frame #{i} contains more than 256 colors!"); } } ReplaceTransparentColor(ref globalColorTable); for (var i = 0; i < Frames.Count; i++) { var frame = Frames[i]; var colorTable = colorTables[i]; var localColorTableFlag = (byte)(colorTable == globalColorTable ? 0 : 1); var localColorTableSize = GetColorTableSize(colorTable); byte transparentColorFlag = 0, transparentColorIndex = 0; byte max; var colorIndexes = GetColorIndexes(frame.Texture, scale, colorTable, localColorTableFlag, ref transparentColorFlag, ref transparentColorIndex, out max); var graphicControlExtension = new GraphicControlExtension(4, 0, (byte)frame.DisposalMethod, 0, transparentColorFlag, (ushort)(100 * frame.Delay), transparentColorIndex); var imageDescriptor = new ImageDescriptor(0, 0, width, height, localColorTableFlag, 0, 0, 0, localColorTableSize); var minCodeSize = LzwEncoder.GetMinCodeSize(max); var lzw = LzwEncoder.Encode(colorIndexes, minCodeSize); var tableBasedImageData = new TableBasedImageData(minCodeSize, lzw); bytes.Clear(); bytes.AddRange(graphicControlExtension.GetBytes()); bytes.AddRange(imageDescriptor.GetBytes()); if (localColorTableFlag == 1) { bytes.AddRange(ColorTableToBytes(colorTable, localColorTableSize)); } bytes.AddRange(tableBasedImageData.GetBytes()); yield return(bytes); } yield return(new List <byte> { 0x3B }); // GIF Trailer. // Then output GIF header as last iterator element! This way we can build global color table "on fly" instead of expensive building operation. var globalColorTableSize = GetColorTableSize(globalColorTable); var logicalScreenDescriptor = new LogicalScreenDescriptor(width, height, 1, 7, 0, globalColorTableSize, 0, 0); bytes.Clear(); bytes.AddRange(Encoding.UTF8.GetBytes(header)); bytes.AddRange(logicalScreenDescriptor.GetBytes()); bytes.AddRange(ColorTableToBytes(globalColorTable, globalColorTableSize)); bytes.AddRange(applicationExtension.GetBytes()); yield return(bytes); }
/// <summary> /// Encode GIF in multiple threads. /// </summary> public void EncodeParallel(Action <EncodeProgress> onProgress, int scale = 1) // TODO: Refact. { if (_free) { throw new Exception("The Free version doesn't support this feature. Please consider buying the Full version of Power GIF."); } const string header = "GIF89a"; var width = (ushort)(Frames[0].Texture.width * scale); var height = (ushort)(Frames[0].Texture.height * scale); var globalColorTable = new List <Color32>(); var applicationExtension = new ApplicationExtension(); var encoded = new Dictionary <int, List <byte> >(); var encodeProgress = new EncodeProgress { FrameCount = Frames.Count }; var colorTables = new List <Color32> [Frames.Count]; var distinctColors = new Dictionary <int, List <Color32> >(); var manualResetEvent = new ManualResetEvent(false); for (var i = 0; i < Frames.Count; i++) { var frame = Frames[i]; ThreadPool.QueueUserWorkItem(context => { var distinct = frame.Texture.GetPixels32().Distinct().ToList(); lock (distinctColors) { distinctColors.Add((int)context, distinct); if (distinctColors.Count == Frames.Count) { manualResetEvent.Set(); } } }, i); } manualResetEvent.WaitOne(); for (var i = 0; i < Frames.Count; i++) { var colors = distinctColors[i]; var add = colors.Where(j => !globalColorTable.Contains(j)).ToList(); if (globalColorTable.Count + add.Count <= 256) { globalColorTable.AddRange(add); colorTables[i] = globalColorTable; } else if (colors.Count <= 256) // Introduce local color table. { colorTables[i] = colors; } else { onProgress(new EncodeProgress { Completed = true, Exception = new Exception($"Frame #{i} contains more than 256 colors!") }); return; } } ReplaceTransparentColor(ref globalColorTable); for (var i = 0; i < Frames.Count; i++) // Don't use Parallel.For to leave .NET compatibility. { ThreadPool.QueueUserWorkItem(context => { var index = (int)context; var colorTable = colorTables[index]; var localColorTableFlag = (byte)(colorTable == globalColorTable ? 0 : 1); var localColorTableSize = GetColorTableSize(colorTable); byte transparentColorFlag = 0, transparentColorIndex = 0; byte max; var colorIndexes = GetColorIndexes(Frames[index].Texture, scale, colorTable, localColorTableFlag, ref transparentColorFlag, ref transparentColorIndex, out max); var graphicControlExtension = new GraphicControlExtension(4, 0, (byte)Frames[index].DisposalMethod, 0, transparentColorFlag, (ushort)(100 * Frames[index].Delay), transparentColorIndex); var imageDescriptor = new ImageDescriptor(0, 0, width, height, localColorTableFlag, 0, 0, 0, localColorTableSize); var minCodeSize = LzwEncoder.GetMinCodeSize(max); var lzw = LzwEncoder.Encode(colorIndexes, minCodeSize); var tableBasedImageData = new TableBasedImageData(minCodeSize, lzw); var bytes = new List <byte>(); bytes.AddRange(graphicControlExtension.GetBytes()); bytes.AddRange(imageDescriptor.GetBytes()); if (localColorTableFlag == 1) { bytes.AddRange(ColorTableToBytes(colorTable, localColorTableSize)); } bytes.AddRange(tableBasedImageData.GetBytes()); lock (encoded) { encoded.Add(index, bytes); encodeProgress.Progress++; if (encoded.Count == Frames.Count) { var globalColorTableSize = GetColorTableSize(globalColorTable); var logicalScreenDescriptor = new LogicalScreenDescriptor(width, height, 1, 7, 0, globalColorTableSize, 0, 0); var binary = new List <byte>(); binary.AddRange(Encoding.UTF8.GetBytes(header)); binary.AddRange(logicalScreenDescriptor.GetBytes()); binary.AddRange(ColorTableToBytes(globalColorTable, globalColorTableSize)); binary.AddRange(applicationExtension.GetBytes()); binary.AddRange(encoded.OrderBy(j => j.Key).SelectMany(j => j.Value)); binary.Add(0x3B); // GIF Trailer. encodeProgress.Bytes = binary.ToArray(); encodeProgress.Completed = true; } onProgress(encodeProgress); } }, i); } }
public static bool IsCompressed(GalImageFormat format) { ImageDescriptor desc = GetImageDescriptor(format); return((desc.BlockWidth | desc.BlockHeight) != 1); }
/// <summary> /// Returns true if the delayer needs to allocate or reallocate memory. /// </summary> public bool NeedsReallocation(ImageDescriptor imageDescriptor, long availableMemory) { return(!allocated || !ImageDescriptor.Compatible(this.imageDescriptor, imageDescriptor) || this.availableMemory != availableMemory); }
private static List <Block> ReadBlocks(byte[] bytes, ref int startIndex) { var blocks = new List <Block>(); var index = startIndex; while (true) { switch (bytes[index]) { case Block.ExtensionIntroducer: { Block extension; switch (bytes[index + 1]) { case Block.PlainTextExtensionLabel: extension = new PlainTextExtension(bytes, ref index); break; case Block.GraphicControlExtensionLabel: extension = new GraphicControlExtension(bytes, ref index); break; case Block.CommentExtensionLabel: extension = new CommentExtension(bytes, ref index); break; case Block.ApplicationExtensionLabel: extension = new ApplicationExtension(bytes, ref index); break; default: throw new NotSupportedException("Unknown extension!"); } blocks.Add(extension); break; } case Block.ImageDescriptorLabel: { var descriptor = new ImageDescriptor(bytes, ref index); blocks.Add(descriptor); if (descriptor.LocalColorTableFlag == 1) { var localColorTable = new ColorTable(descriptor.LocalColorTableSize, bytes, ref index); blocks.Add(localColorTable); } var data = new TableBasedImageData(bytes, ref index); blocks.Add(data); break; } case 0x3B: // End { return(blocks); } default: throw new NotSupportedException($"Unsupported GIF block: {bytes[index]:X}."); } } }
public void UpdateSubframes(ImageDescriptor imageDescriptor, int totalFrames) { SetConfiguration(imageDescriptor, totalFrames, imageCount); }
/// <summary> /// Find the Amazon machine image identified by the ImageDescriptor. /// </summary> /// <param name="ec2Client">The EC2 client used to search for the image.</param> /// <param name="descriptor">The descriptor used to identify the image.</param> /// <returns>The Amazon machine image.</returns> public static Image FindImage(AmazonEC2 ec2Client, ImageDescriptor descriptor) { if (ec2Client == null) { throw new ArgumentNullException("ec2Client"); } if (descriptor == null) { throw new ArgumentNullException("descriptor"); } int retryCount = 1; Image image = null; do { var result = ec2Client.DescribeImages(new DescribeImagesRequest() { Owner = new List <string>() { "amazon" }, Filter = new List <Filter>() { new Filter() { Name = "name", Value = new List <string>() { descriptor.NamePrefix } } } }).DescribeImagesResult; if (result.Image.Count != 0) { image = result.Image.OrderByDescending(x => x.Name).First(); } else { // backing control file may be outdated, reload and try once more if (retryCount == 1) { LOGGER.InfoFormat("FindImage - DescribeImages call for image descriptor '{0}' (name prefix '{1}') yielded no results, assuming outdated control file and reloading", descriptor.DefinitionKey, descriptor.NamePrefix); LoadDefinitionsFromWeb(); } retryCount++; } } while (image == null && retryCount <= 2); if (image == null) { LOGGER.InfoFormat("FindImage - failed to find valid AMI image for descriptor '{0}' (name prefix '{1}')", descriptor.DefinitionKey, descriptor.NamePrefix); } return(image); }
private static AmazonEC2Config CreateConfigFromClient(IAmazonEC2 ec2Client, ImageDescriptor descriptor) { if (ec2Client == null) throw new ArgumentNullException("ec2Client"); if (descriptor == null) throw new ArgumentNullException("descriptor"); var config = ConfigFromClient(ec2Client); return config; }
public void SetImageDescriptor(ImageDescriptor imageDescriptor) { this.imageDescriptor = imageDescriptor; }
public static MarkerOptions CreateTintedMarkerOptions() { return(new MarkerOptions() .Icon(ImageDescriptor.DefaultMarker(ImageDescriptor.HUE_AZURE))); }
public static MarkerOptions RandomColorMarkerOptions(LatLng point) { return(new MarkerOptions() .Position(point) .Icon(ImageDescriptor.DefaultMarker(Random.Range(0, 360)))); }
/// <summary> /// Find the Amazon machine image identified by the ImageDescriptor. /// </summary> /// <param name="ec2Client">The EC2 client used to search for the image.</param> /// <param name="descriptor">The descriptor used to identify the image.</param> /// <returns>The Amazon machine image.</returns> public static Image FindImage(IAmazonEC2 ec2Client, ImageDescriptor descriptor) { AmazonEC2Config config = CreateConfigFromClient(ec2Client, descriptor); LoadDefinitionsFromWeb(config); int retryCount = 1; Image image = null; do { var result = ec2Client.DescribeImages(CreateDescribeImagesRequest(descriptor)); if (result.Images.Any()) image = result.Images.OrderByDescending(x => x.Name).First(); else { // backing control file may be outdated, reload and try once more if (retryCount == 1) { Logger.InfoFormat("FindImage - DescribeImages call for image descriptor '{0}' (name prefix '{1}') yielded no results, assuming outdated control file and reloading", descriptor.DefinitionKey, descriptor.NamePrefix); lock (LOCK_OBJECT) { ImageDefinitionsLoaded = false; } LoadDefinitionsFromWeb(config); } retryCount++; } } while (image == null && retryCount <= 2); if (image == null) Logger.InfoFormat("FindImage - failed to find valid AMI image for descriptor '{0}' (name prefix '{1}')", descriptor.DefinitionKey, descriptor.NamePrefix); return image; }
/// <summary> /// Adds a button to the tool bar with the given <paramref name="label"/> and the given <paramref name="image"/>. /// If the button is clicked, the given <paramref name="actionHandler"/> is invoked. /// </summary> /// <param name="label">Label of the button</param> /// <param name="image">Image to use for the button</param> /// <param name="actionHandler">Action handler</param> /// <param name="toolTipText">Additional tooltip text. When NULL <paramref name="label"/> is used as tooltip text</param> public void AddButton(string label, ImageDescriptor image, IActionHandler actionHandler, string toolTipText = null) { AddButton(label, (image == null ? null : image.ImageStream), actionHandler, toolTipText); }