public void ShowGif(string _imgPath) { FileStream fsImg = new FileStream(_imgPath, FileMode.Open); MemoryStream gif = new MemoryStream(); fsImg.CopyTo(gif); fsImg.Close(); byte[] buffer = new byte[gif.Length]; gif.Position = 0; gif.Read(buffer, 0, Convert.ToInt32(gif.Length)); //判断图片是否为GIF格式,通过图片的前三个字节标识位来判断 if (!ASCIIEncoding.ASCII.GetString(buffer, 0, 3).ToLower().Equals("gif")) { MessageBox.Show("无效的GIF图片!"); return; } //清空容器 spFrames.Children.Clear(); spGifImage.Children.Clear(); bd = new GifBitmapDecoder(gif, BitmapCreateOptions.None, BitmapCacheOption.Default); ShowGifInfo(buffer, _imgPath); //显示图片的信息 //显示图片的所有帧 for (int i = 0; i < bd.Frames.Count(); i++) { System.Windows.Controls.Image img = new System.Windows.Controls.Image(); img.Source = bd.Frames[i]; img.Width = 200; img.Height = 200; img.Margin = new Thickness(6, 0, 0, 0); spFrames.Children.Add(img); } GifImage gifImage = new GifImage(); gifImage.Source = _imgPath; spGifImage.Children.Add(gifImage); }
//load事件 private void UserControl_Loaded(object sender, RoutedEventArgs e) { try { SysBLL.Player("插入燃气卡.wav"); }catch (Exception ex) { log.Write("error:FormGasGoldenCardStep02:UserControl_Loaded:" + ex.Message); } try { waterImage = null; waterImage = new GifImage(System.AppDomain.CurrentDomain.BaseDirectory + "\\sysImage\\GIF\\gasGIF\\jinkaGIF\\IC.gif"); this.waterImage.Height = 500; Popup dd = new Popup(); if (imgGrid.Children.Contains(waterImage)) { imgGrid.Children.Remove(waterImage); } imgGrid.Children.Add(waterImage); this.waterImage.StartAnimate(); } catch (Exception ex) { log.Write("error:金卡初始化:" + ex.Message + ex.InnerException); } }
public BRGifMapRenderer(IMap map, Point targetSize, string filePath, int frameDelay = 10) : base(map, targetSize) { FilePath = filePath; FrameDelay = frameDelay; var ms = new MemoryStream(); GifImage = new GifImage(ms); GifImage.DefaultFrameDelay = FrameDelay; GifImage.DefaultWidth = targetSize[0]; GifImage.DefaultHeight = targetSize[1]; Brushes = new Dictionary <Color, Brush>(); foreach (var color in Colors) { Brushes.Add(color.Value, new SolidBrush(color.Value)); } var initialImage = new Bitmap(targetSize[0], targetSize[1]); //var initialGraphics = Graphics.FromImage(initialImage); //initialGraphics.FillRectangle(new SolidBrush(Color.Red), new Rectangle(0,0,initialImage.Width, initialImage.Height)); GifImage.AddFrame(initialImage, FrameDelay); }
public void UpdateWeather() { Dispatcher.UIThread.InvokeAsync(() => { Rectangle dim = this.FindControl <Rectangle>("WeatherDim"); Image gif = this.FindControl <Image>("WeatherGif"); Uri uri = new Uri($"resm:Kermalis.PokemonBattleEngineClient.MISC.WEATHER_{battleView.Client.Battle.Weather}.gif?assembly=PokemonBattleEngineClient"); switch (battleView.Client.Battle.Weather) { case PBEWeather.Hailstorm: dim.Fill = hailstormDim; GifImage.SetSourceUri(gif, uri); dim.IsVisible = gif.IsVisible = true; break; case PBEWeather.HarshSunlight: dim.Fill = harshSunlightDim; dim.IsVisible = true; gif.IsVisible = false; break; case PBEWeather.Rain: dim.Fill = rainDim; GifImage.SetSourceUri(gif, uri); dim.IsVisible = gif.IsVisible = true; break; case PBEWeather.Sandstorm: dim.Fill = sandstormDim; dim.IsVisible = true; gif.IsVisible = false; break; default: dim.IsVisible = gif.IsVisible = false; break; } }); }
public void Draw(IDataModel dataModel, DrawingContext c, bool preview, bool updateAnimations) { if (LayerType != LayerType.Keyboard && LayerType != LayerType.KeyboardGif) { return; } // Preview simply shows the properties as they are. When not previewing they are applied var appliedProperties = !preview ? Properties.GetAppliedProperties(dataModel) : Properties.GetAppliedProperties(dataModel, true); // Update animations AnimationUpdater.UpdateAnimation((KeyboardPropertiesModel)Properties, updateAnimations); if (LayerType == LayerType.Keyboard) { Drawer.Draw(c, (KeyboardPropertiesModel)Properties, appliedProperties); } else if (LayerType == LayerType.KeyboardGif) { GifImage = Drawer.DrawGif(c, (KeyboardPropertiesModel)Properties, appliedProperties, GifImage); } }
public ScanningWindow(MainWindow mainWindow, List <Event> events, List <Participant> participants) { InitializeComponent(); this.FormClosed += CloseHandler; this.mainWindow = mainWindow; this.participants = participants; this.events = events; imagePath = Directory.GetParent(workingDirectory).Parent.FullName + @"\UI\Images\qr-scan.gif"; gifImage = new GifImage(imagePath, 264, 132); gifImage.ReverseAtEnd = false; PictureBox_Barcode.Image = gifImage.GetNextFrame(); PictureBox_Barcode.BringToFront(); this.ActiveControl = TextBox_Barcode; bool toMaximize = WindowHelper.checkIfMaximizeWindow(this.Width, this.Height); if (toMaximize) { this.WindowState = FormWindowState.Maximized; } BringToFront(); }
private void load() { try { try { gifImg = null; if (ConfigSysUtils.getReadCardGif() != null) { gifImg = new GifImage(System.AppDomain.CurrentDomain.BaseDirectory + ConfigSysUtils.getReadCardGif()); this.gifImg.Height = 500; if (imgGrid.Children.Contains(gifImg)) { imgGrid.Children.Remove(gifImg); } imgGrid.Children.Add(gifImg); this.gifImg.StartAnimate(); } else { this.yhCardImg.Height = 500; if (imgGrid.Children.Contains(yhCardImg)) { imgGrid.Children.Remove(yhCardImg); } imgGrid.Children.Add(yhCardImg); this.yhCardImg.StartAnimate(); } } catch (Exception ex) { } cardImg.Visibility = Visibility.Hidden; if (SysBLL.payCostType == 3) { PrintInfo("请将银行卡插入银行读卡器"); SysBLL.Player("插入银行卡.wav"); } else { PrintInfo("请将甘肃一卡通或银行卡插入银行读卡器"); SysBLL.Player("请插入银行卡或惠民卡.wav"); } //if (SysBLL.payCostType == 12) //{ // if (imgGrid.Children.Contains(yhCardImg)) imgGrid.Children.Remove(prop2WaterImg); // imgGrid.Children.Add(prop2WaterImg); // this.prop2WaterImg.StartAnimate(); //} readThread = new Thread(delegate() { readCard(); }); setBankTipThread = new Thread(delegate() { //设置提示信息 //showBankTip(); }); readThread.Start(); setBankTipThread.Start(); } catch (Exception ex) { log.Write("error:插卡页面异常:" + ex.Message); } }
/// <summary> /// Raised when a new index is selected from ImageSelector. /// Loads the GIF file of that filename. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The event data.</param> private void ImageSelector_SelectedIndexChanged(object sender, EventArgs e) { if (!SavePrompt()) { return; } var wasPlaying = Indexer.Playing; Indexer.Playing = false; loaded = false; changed = false; filePath = Path.Combine(filesPath, (string)ImageSelector.Items[ImageSelector.SelectedIndex]); if (gifImage != null) { foreach (GifFrame <Bitmap> frame in gifImage.Frames) { frame.Image.Dispose(); } } if (desiredFrames != null) { foreach (Bitmap frame in desiredFrames) { frame.Dispose(); } } gifImage = null; frameIndex = -1; desiredFrames = null; ImageComparison.Panel1.BackgroundImage = null; ImageComparison.Panel2.BackgroundImage = null; ImageSourceColor.BackColor = Color.Transparent; ImageDesiredColor.BackColor = Color.Transparent; ImageSourcePalette.BackColor = PaletteControls.BackColor; ImageDesiredPalette.BackColor = PaletteControls.BackColor; ImageSourcePalette.Controls.Clear(); ImageDesiredPalette.Controls.Clear(); foreach (Panel panel in sourceSwatches) { panel.Dispose(); } foreach (Panel panel in desiredSwatches) { panel.Dispose(); } sourceSwatches.Clear(); desiredSwatches.Clear(); SourceAlphaCode.ResetText(); SourceColorCode.ResetText(); DesiredAlphaCode.ResetText(); DesiredColorCode.ResetText(); FrameControls.Enabled = false; PaletteControls.Enabled = false; ColorControls.Enabled = false; ErrorLabel.Visible = false; currentColor = Color.Empty; FileStream gifStream = null; try { gifStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); gifImage = GifImage.OfBitmap(gifStream); } catch (Exception) { Console.WriteLine("An error occurred attempting to load the file: " + filePath); ShowError("An error occurred attempting to load this file."); return; } finally { if (gifStream != null) { gifStream.Dispose(); } } Indexer.UseTimingsFrom(gifImage); var map = new AlphaRemappingTable(); var mapFile = Path.ChangeExtension(filePath, AlphaRemappingTable.FileExtension); if (File.Exists(mapFile)) { map.LoadMap(mapFile); } colorMappingTable.Clear(); foreach (var frame in gifImage.Frames) { BuildColorMap(frame.GetColorTable(), map); } sourceSwatches.Capacity = colorMappingTable.Count; desiredSwatches.Capacity = colorMappingTable.Count; var swatchSize = ImageSourcePalette.Height - 2; var size = new Size(swatchSize, swatchSize); var location = new Point(1, 1); ImageSourcePalette.SuspendLayout(); ImageDesiredPalette.SuspendLayout(); var mappingIndex = 0; foreach (var colorMapping in colorMappingTable) { var sourcePanel = new Panel() { Size = size, Location = location }; var desiredPanel = new Panel() { Size = size, Location = location }; sourcePanel.Tag = desiredPanel; desiredPanel.Tag = sourcePanel; sourceSwatches.Add(sourcePanel); desiredSwatches.Add(desiredPanel); ImageSourcePalette.Controls.Add(sourcePanel); ImageDesiredPalette.Controls.Add(desiredPanel); sourceSwatches[mappingIndex].Click += Swatch_Clicked; desiredSwatches[mappingIndex].Click += Swatch_Clicked; sourceSwatches[mappingIndex].BackColor = colorMapping.Key; desiredSwatches[mappingIndex].BackColor = colorMapping.Value; if (mappingIndex == 0) { currentColor = colorMapping.Key; } mappingIndex++; location.X += swatchSize + 1; } location.Y = 0; var blankSourcePanel = new Panel() { Size = ImageSourcePalette.Size, Location = location, BackColor = SystemColors.Control }; ImageSourcePalette.Controls.Add(blankSourcePanel); var blankDesiredPanel = new Panel() { Size = ImageDesiredPalette.Size, Location = location, BackColor = SystemColors.Control }; ImageDesiredPalette.Controls.Add(blankDesiredPanel); ImageSourcePalette.ResumeLayout(); ImageDesiredPalette.ResumeLayout(); ImageSourcePalette.BackColor = ImageComparison.BackColor; ImageDesiredPalette.BackColor = ImageComparison.BackColor; desiredFrames = new Bitmap[gifImage.Frames.Length]; for (var i = 0; i < desiredFrames.Length; i++) { desiredFrames[i] = (Bitmap)gifImage.Frames[i].Image.Clone(); } UpdateDesiredFrames(); FrameControls.Enabled = true; PaletteControls.Enabled = true; ColorControls.Enabled = true; SaveCommand.Enabled = true; UpdateSelectedFrame(0); UpdateColorHex(); UpdateColorDisplay(); if (wasPlaying) { Indexer.Playing = true; } loaded = true; }
public static void Animate(GifImage image, EventHandler onFrameChangedHandler) { if (image == null) { return; } GifImageInfo imageInfo; // See comment in the class header about locking the image ref. lock (image) { // could we avoid creating an ImageInfo object if FrameCount == 1 ? imageInfo = new GifImageInfo(image); } // If the image is already animating, stop animating it StopAnimate(image, onFrameChangedHandler); // Acquire a writer lock to modify the image info list. If the thread has a reader lock we need to upgrade // it to a writer lock; acquiring a reader lock in this case would block the thread on itself. // If the thread already has a writer lock its ref count will be incremented w/o placing the request in the // writer queue. See ReaderWriterLock.AcquireWriterLock method in the MSDN. var readerLockHeld = RwImgListLock.IsReaderLockHeld; var lockDowngradeCookie = new LockCookie(); ThreadWriterLockWaitCount++; try { if (readerLockHeld) { lockDowngradeCookie = RwImgListLock.UpgradeToWriterLock(Timeout.Infinite); } else { RwImgListLock.AcquireWriterLock(Timeout.Infinite); } } finally { ThreadWriterLockWaitCount--; } try { if (imageInfo.Animated) { // Construct the image array // if (ImageInfoList == null) { ImageInfoList = new List <GifImageInfo>(); } // Add the new image // imageInfo.FrameChangedHandler = onFrameChangedHandler; ImageInfoList.Add(imageInfo); // Construct a new timer thread if we haven't already // if (AnimationThread == null) { AnimationThread = new Thread(AnimateImages50Ms) { Name = typeof(ImageAnimator).Name, IsBackground = true }; AnimationThread.Start(); } } } finally { if (readerLockHeld) { RwImgListLock.DowngradeFromWriterLock(ref lockDowngradeCookie); } else { RwImgListLock.ReleaseWriterLock(); } } }
public void ClearActiveItem() { m_activeItem = null; m_selectedGif = null; }
void m_addFilesButton_Click(object sender, RoutedEventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = Filter; dlg.Multiselect = MultiSelect; if (!MultiUpload) { dlg.Multiselect = false; } if ((bool)dlg.ShowDialog()) { if (!MultiUpload) { m_files.Clear(); } if (CheckUploadFilesEvent != null) { CheckUploadFileEventArgs checkArgs = new CheckUploadFileEventArgs(new List <FileInfo>(dlg.Files)); CheckUploadFilesEvent(this, checkArgs); if (checkArgs.CheckResult == false) { return; } } BitmapSource imageSource = null; foreach (FileInfo file in dlg.Files) { string fileName = file.Name.ToLower().Trim(); var suffix = file.Extension; //如果文件没有后缀名,需要提示User if (string.IsNullOrEmpty(suffix)) { this.ShowMessage(MessageResource.Uploader_InvalidFileExtension, Newegg.Oversea.Silverlight.Controls.Components.MessageType.Warning); continue; } if (!this.Filter.Contains("*.*") && !this.Filter.ToLower().Contains(suffix.ToLower())) { this.ShowMessage(MessageResource.Uploader_InvalidFileExtension, Newegg.Oversea.Silverlight.Controls.Components.MessageType.Warning); continue; } try { using (file.OpenRead()) { if (fileName.EndsWith("jpg") || fileName.EndsWith("jpeg") || fileName.EndsWith("png")) { imageSource = new BitmapImage(); using (var stream = file.OpenRead()) { try { imageSource.SetSource(stream); } catch { //捕获特定异常,比如把a.xls改成a.jpg,此时需要给一个友好提示 this.ShowMessage(MessageResource.Uploader_InvalidImageType, Newegg.Oversea.Silverlight.Controls.Components.MessageType.Warning); continue; } } } else if (fileName.EndsWith("gif")) { GifImage gif = null; using (var stream = file.OpenRead()) { try { gif = GIFDecoder.Decode(stream); } catch { //捕获特定异常,比如把a.jpg改成a.gif,此时需要给一个友好提示 this.ShowMessage(MessageResource.Uploader_InvalidImageType, Newegg.Oversea.Silverlight.Controls.Components.MessageType.Warning); continue; } if (gif.Frames.Count > 0) { imageSource = gif.Frames[0].Image; }//如果user把jpg文件的后缀修改为.gif,需要抛异常提示User else { this.ShowMessage(MessageResource.Uploader_InvalidImageType, Newegg.Oversea.Silverlight.Controls.Components.MessageType.Warning); continue; } } } } }//检查文件是否正在使用 catch (IOException) { this.ShowMessage(MessageResource.Uploader_FileInUsed, Newegg.Oversea.Silverlight.Controls.Components.MessageType.Error); continue; } //Catch other exception catch (Exception ex) { this.ShowMessage(ex.Message, Newegg.Oversea.Silverlight.Controls.Components.MessageType.Error); continue; } //check image width and height if (this.DimensionsMatch != DimensionsMatchType.None) { if (fileName.EndsWith("jpg") || fileName.EndsWith("png") || fileName.EndsWith("gif") || fileName.EndsWith("jpeg") || fileName.EndsWith("bmp")) { try { if (imageSource != null) { CheckImageDimensions(imageSource, file); } } // Catch check exception catch (ArgumentException ex) { this.ShowMessage(ex.Message, Newegg.Oversea.Silverlight.Controls.Components.MessageType.Warning); continue; } } } FileUpload upload = new FileUpload(this.Dispatcher, UploadUrl, file, this); upload.UploadCanceled += (o, b) => { if (this.UploadCanceled != null) { UploadCanceled(this, b); } }; upload.CanEditFileName = CanEditFileName; if (UploadChunkSize > 0) { upload.ChunkSize = UploadChunkSize; } if (MaximumFileNameLength > 0 && upload.File.Name.Length > MaximumFileNameLength) { this.ShowMessage(string.Format(MessageResource.Uploader_GreaterThanMaximumFileNameLength, upload.Name, upload.File.Name.Length, this.MaximumFileNameLength), Newegg.Oversea.Silverlight.Controls.Components.MessageType.Warning); continue; } //单个文件超过限制的大小 if (MaximumUploadBytes >= 0 && upload.FileLength > MaximumUploadBytes) { this.ShowMessage(string.Format(MessageResource.Uploader_OutOfSingleAvailableUploadSize, upload.Name, this.MaximumUploadSize), Newegg.Oversea.Silverlight.Controls.Components.MessageType.Warning); continue; } //全部的文件Size超过限制大小 if (MaximumTotalUploadBytes >= 0 && TotalUploadSize + upload.FileLength > MaximumTotalUploadBytes) { this.ShowMessage(string.Format(MessageResource.Uploader_OutOfTotalAvailableUploadSize, this.MaximumTotalUploadSize), Newegg.Oversea.Silverlight.Controls.Components.MessageType.Warning); break; } //多文件上传的时候才作此Check if (MaxNumberToUpload > -1 && MultiUpload) { if (++m_count > MaxNumberToUpload) { this.ShowMessage(string.Format(MessageResource.Uploader_OutOfMaximumNumber, this.MaxNumberToUpload), Newegg.Oversea.Silverlight.Controls.Components.MessageType.Warning); break; } } upload.DisplayThumbnail = (bool)this.m_displayThumbailCheckBox.IsChecked; if (!this.AllowThumbnail) { upload.DisplayThumbnail = false; } upload.StatusChanged += new EventHandler(upload_StatusChanged); upload.UploadProgressChanged += new ProgressChangedEvent(upload_UploadProgressChanged); upload.UploadCompleted += new UploadCompletedEvent(upload_UploadCompleted); m_files.Add(upload); this.m_borderBackground.Visibility = System.Windows.Visibility.Collapsed; } } }
public static void StopAnimate(GifImage image, EventHandler onFrameChangedHandler) { // Make sure we have a list of images if (image == null || ImageInfoList == null) { return; } // Acquire a writer lock to modify the image info list - See comments on Animate() about this locking. var readerLockHeld = RwImgListLock.IsReaderLockHeld; var lockDowngradeCookie = new LockCookie(); ThreadWriterLockWaitCount++; try { if (readerLockHeld) { lockDowngradeCookie = RwImgListLock.UpgradeToWriterLock(Timeout.Infinite); } else { RwImgListLock.AcquireWriterLock(Timeout.Infinite); } } finally { ThreadWriterLockWaitCount--; } try { // Find the corresponding reference and remove it for (var i = 0; i < ImageInfoList.Count; i++) { var imageInfo = ImageInfoList[i]; if (Equals(image, imageInfo.Image)) { if (onFrameChangedHandler == imageInfo.FrameChangedHandler || onFrameChangedHandler != null && onFrameChangedHandler.Equals(imageInfo.FrameChangedHandler)) { ImageInfoList.Remove(imageInfo); } break; } } if (!ImageInfoList.Any()) { AnimationThread?.Join(); AnimationThread = null; } } finally { if (readerLockHeld) { RwImgListLock.DowngradeFromWriterLock(ref lockDowngradeCookie); } else { RwImgListLock.ReleaseWriterLock(); } } }
/// <summary> /// 合并多个gif动画,在空间坐标上 /// </summary> /// <param name="sourceGifs">原图像</param> /// <param name="outPath">合并后图像</param> public static void Merge(List <string> sourceGifs, string outPath) { List <List <GifFrame> > frames = new List <List <GifFrame> >(); foreach (string source in sourceGifs) { if (!File.Exists(source)) { throw new IOException(string.Format("文件{0}不存在!", source)); } using (Bitmap ora_Img = new Bitmap(source)) { if (ora_Img.RawFormat.Guid != ImageFormat.Gif.Guid) { throw new IOException(string.Format("文件{0}!", source)); } } GifImage gifImage = GifDecoder.Decode(source); ThinkDisposalMethod(gifImage); int index = 0; foreach (GifFrame f in gifImage.Frames) { if (frames.Count <= index) { List <GifFrame> list = new List <GifFrame>(); frames.Add(list); } List <GifFrame> frameList = frames[index]; frameList.Add(f); index++; } } List <GifFrame> frameCol = new List <GifFrame>(); int frameIndex = 0; foreach (List <GifFrame> fs in frames) { GifFrame frame = Merge(fs); frameCol.Add(frame); if (frame.Image.Width != frameCol[0].Image.Width || frame.Image.Height != frameCol[0].Image.Height) { frame.ImageDescriptor.XOffSet = frames[frameIndex][0].ImageDescriptor.XOffSet; frame.ImageDescriptor.YOffSet = frames[frameIndex][0].ImageDescriptor.YOffSet; frame.GraphicExtension.DisposalMethod = frames[frameIndex][0].GraphicExtension.DisposalMethod; } frame.GraphicExtension.Delay = frame.Delay = frames[frameIndex][0].Delay; frameIndex++; } GifImage gifImg = new GifImage(); gifImg.Header = "GIF89a"; LogicalScreenDescriptor lcd = new LogicalScreenDescriptor(); lcd.Width = (short)frameCol[0].Image.Width; lcd.Height = (short)frameCol[0].Image.Height; gifImg.LogicalScreenDescriptor = lcd; ApplicationEx ape = new ApplicationEx(); List <ApplicationEx> apps = new List <ApplicationEx>(); apps.Add(ape); gifImg.ApplictionExtensions = apps; gifImg.Frames = frameCol; GifEncoder.Encode(gifImg, outPath); }
/// <summary> /// 对gif动画添加水印 /// </summary> /// <param name="gifFilePath">原gif动画的路径</param> /// <param name="sizeMode"></param> /// <param name="text">水印文字</param> /// <param name="textForceColor">水印文字的颜色,因为gif不是真彩色图片,所以在显示的时候,该颜色可能有所误差,但基本上可以确定颜色范围</param> /// <param name="font">字体</param> /// <param name="x">水印位置横坐标</param> /// <param name="y">水印位置纵坐标</param> /// <param name="outputPath">输出路径</param> public static void WaterMark(string gifFilePath, SizeMode sizeMode, string text, Color textForceColor, Font font, float x, float y, string outputPath) { if (!File.Exists(gifFilePath)) { throw new IOException(string.Format("文件{0}不存在!", gifFilePath)); } using (Bitmap ora_Img = new Bitmap(gifFilePath)) { if (ora_Img.RawFormat.Guid != ImageFormat.Gif.Guid) { throw new IOException(string.Format("文件{0}!", gifFilePath)); } } GifImage gifImage = GifDecoder.Decode(gifFilePath); if (sizeMode == SizeMode.Large) { ThinkDisposalMethod(gifImage); } Color textColor = textForceColor; int frameCount = 0; foreach (GifFrame f in gifImage.Frames) { if ((sizeMode == SizeMode.Normal && frameCount++ == 0) || sizeMode == SizeMode.Large) { Graphics g = Graphics.FromImage(f.Image); g.DrawString(text, font, new SolidBrush(textColor), new PointF(x, y)); g.Dispose(); bool hasTextColor = false; Color32[] colors = PaletteHelper.GetColor32s(f.LocalColorTable); foreach (Color32 c in colors) { if (c.ARGB == textColor.ToArgb()) { hasTextColor = true; break; } } if (!hasTextColor) { if (f.Palette.Length < 256) { int newSize = f.Palette.Length * 2; Color32[] newColors = new Color32[newSize]; newColors[f.Palette.Length] = new Color32(textColor.ToArgb()); Array.Copy(colors, newColors, colors.Length); byte[] lct = new byte[newColors.Length * 3]; int index = 0; foreach (Color32 c in newColors) { lct[index++] = c.Red; lct[index++] = c.Green; lct[index++] = c.Blue; } f.LocalColorTable = lct; f.ImageDescriptor.LctFlag = true; f.ImageDescriptor.LctSize = newSize; f.ColorDepth = f.ColorDepth + 1; } else { OcTreeQuantizer q = new OcTreeQuantizer(8); Color32[] cs = q.Quantizer(f.Image); byte[] lct = new byte[cs.Length * 3]; int index = 0; int colorCount = 0; foreach (Color32 c in cs) { lct[index++] = c.Red; lct[index++] = c.Green; lct[index++] = c.Blue; if (c.ARGB == f.BgColor.ARGB) { f.GraphicExtension.TranIndex = (byte)colorCount; } colorCount++; } Quantizer(f.Image, cs); f.LocalColorTable = lct; f.ImageDescriptor.LctFlag = true; f.ImageDescriptor.LctSize = 256; f.ColorDepth = 8; } } } } GifEncoder.Encode(gifImage, outputPath); }
/// <summary> /// Creates an <see cref="T:DesktopSprites.SpriteManagement.AnimatedImage`1"/> from a GIF file. /// </summary> /// <param name="frameFactory">The method used to construct a TFrame object for each frame in a GIF animation.</param> /// <param name="allowableDepths">The allowable set of depths for the raw buffer. Use as many as your output format permits. The /// Indexed8Bpp format is required.</param> private void AnimatedImageFromGif(BufferToImage <T> frameFactory, BitDepths allowableDepths) { GifImage <T> gifImage; using (FileStream imageStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read)) gifImage = new GifImage <T>(imageStream, frameFactory, allowableDepths); Size = gifImage.Size; LoopCount = gifImage.Iterations; ImageDuration = gifImage.Duration; int frameCount = gifImage.Frames.Length; var framesList = new List <T>(frameCount); var durationsList = new List <int>(frameCount); var frameIndexesList = new List <int>(frameCount); var frameHashesList = new List <int>(frameCount); for (int sourceFrame = 0; sourceFrame < frameCount; sourceFrame++) { int frameDuration = gifImage.Frames[sourceFrame].Duration; // Decoding the GIF may have produced frames of zero duration, we can safely drop these. // If the file has all-zero durations, we're into the land of undefined behavior for animations. // If we get to the last frame and we have nothing so far, we'll use that just so there is something to display. // Alternatively, in an image with only one frame, then only this frame ever need be displayed. if (frameDuration == 0 && !(ImageDuration == 0 && sourceFrame == frameCount - 1)) { // Dispose of unused frame. IDisposable disposable = gifImage.Frames[sourceFrame].Image as IDisposable; if (disposable != null) { disposable.Dispose(); } continue; } durationsList.Add(frameDuration); // Determine if all frames share the same duration. if (sourceFrame == 0) { commonFrameDuration = frameDuration; } else if (commonFrameDuration != frameDuration) { commonFrameDuration = -1; } // Calculate the frame hash to check if a duplicate frame exists. // This will update our collection and given hash list appropriately. AddOrReuseFrame(gifImage.Frames[sourceFrame], framesList, frameIndexesList, frameHashesList); } frames = framesList.ToImmutableArray(); if (frames.Length != frameIndexesList.Count) { frameIndexes = frameIndexesList.ToImmutableArray(); } if (commonFrameDuration == -1) { durations = durationsList.ToImmutableArray(); } }
private void hbAddImage_Click(object sender, RoutedEventArgs e) { OpenFileDialog openDialog = new OpenFileDialog(); if (openDialog.ShowDialog() == true) { using (Stream stream = openDialog.File.OpenRead()) { // Don't allow big files. if (stream.Length > 5000000) { MessageBox.Show("图片尺寸必须小于5MB."); } else { ////BitmapImage image = new BitmapImage(); ////byte[] data = new byte[stream.Length]; ////stream.Read(data, 0, (int)stream.Length); ////tmpImageName = openDialog.File.Name.ToString(); ////tmpImageStream = data; ////image.SetSource(stream); ////imgLoad.Source = image; ////imgLoad.Visibility = Visibility.Visible; ////stream.Close(); string fileExtension = System.IO.Path.GetExtension(openDialog.File.Name.ToString()); BitmapImage image = new BitmapImage(); byte[] data = new byte[stream.Length]; //stream.Read(data, 0, (int)stream.Length); //tmpImageName = openDialog.File.Name.ToString(); //tmpImageStream = data; ////image.SetSource(stream); ////imgOwner.Source = image; //stream.Close(); GifImage tmpgif = null; if (fileExtension == ".gif") { //stream.Read(data, 0, (int)stream.Length); //ExtendedImage extendedImage = new ExtendedImage(); //extendedImage.SetSource(stream); //cusImage.Source = extendedImage; tmpgif = GIFDecoder.Decode(stream); tmpImageName = openDialog.File.Name.ToString(); for (int count = 0; count < tmpgif.Frames.Count; count++) { imgLoad.Source = tmpgif.Frames[count].Image; imgLoad.Visibility = Visibility.Visible; //imgOwner.Source = tmpgif.Frames[count].Image; //image.SetSource(imgOwner.Source); } //byte[] data = new byte[stream.Length]; stream.Read(tmpgif.GlobalColorTable, 0, (int)tmpgif.GlobalColorTable.Length); tmpImageStream = tmpgif.GlobalColorTable; //image.SetSource(stream); } else { stream.Read(data, 0, (int)stream.Length); tmpImageName = openDialog.File.Name.ToString(); tmpImageStream = data; image.SetSource(stream); imgLoad.Source = image; imgLoad.Visibility = Visibility.Visible; } stream.Close(); } } } }
public override void LoadData() { foreach (object obj in Params.Objects.Where(obj => obj != null)) { if (obj.GetType() == typeof(FormResultData)) { data = (FormResultData)obj; } } data.log.Write(LogMessageType.Information, "========================НАЧАЛО ОБСЛУЖИВАНИЯ=========================="); if (Globals.ClientConfiguration.Settings.style == 1) { gifImage = new GifImage(Globals.GetPath(PathEnum.Image) + "\\" + Globals.DesignConfiguration.Settings.ButtonGetOxigen); gifImage.ReverseAtEnd = false; //dont reverse at end } else { Globals.DesignConfiguration.Settings.LoadPictureBox(pBxGiveOxigen, Globals.DesignConfiguration.Settings.ButtonGetOxigen_style1); } //Globals.DesignConfiguration.Settings.LoadPictureBox(pBxGiveOxigen, Globals.DesignConfiguration.Settings.ButtonGetOxigen); Globals.DesignConfiguration.Settings.LoadPictureBox(pBxReturnBack, Globals.DesignConfiguration.Settings.ButtonRetToMain); AmountServiceText.Text = "Внесено: 0 руб."; AmountServiceText.ForeColor = System.Drawing.Color.Red; SecondMessageText.Text = ""; LabelNameService2.Text = Globals.ClientConfiguration.Settings.services[data.numberService].caption; TextPayBill.LoadFile(Globals.GetPath(PathEnum.Text) + "\\WaitPayBill.rtf"); // сразу проверим - если авторизовались и достаточно денег на счете - сразу списываем деньги со счета if (data.retLogin != "") { int sum = GlobalDb.GlobalBase.GetUserMoney(data.CurrentUserId); data.log.Write(LogMessageType.Information, "ACCOUNT: На счету у пользователя " + data.retLogin + " " + sum + " руб."); if (sum >= data.serv.price) { // денег на счете достаточно data.log.Write(LogMessageType.Information, "ACCOUNT: Оказываем услугу с денег со счета..."); amount += data.serv.price; AmountServiceText.Text = "Внесено: " + data.serv.price + " руб."; AmountServiceText.ForeColor = System.Drawing.Color.Green; SecondMessageText.Text = "Остаток на счете: " + (sum - data.serv.price) + " руб."; data.log.Write(LogMessageType.Information, "ACCOUNT: Внесли достаточную для оказания услуги сумму со счета."); // все можно уже пользоваться pBxGiveOxigen.Enabled = true; moneyFixed = false; StopHardware = true; // обновим счет GlobalDb.GlobalBase.AddToAmount(data.CurrentUserId, 0 - data.serv.price); pBxReturnBack.Enabled = false; return; } else if (sum > 0) { // денег не достаточно - все равно списываем все подчистую data.log.Write(LogMessageType.Information, "ACCOUNT: Оказываем услугу с денег со счета..."); amount += sum; AmountServiceText.Text = "Внесено: " + sum + " руб."; SecondMessageText.Text = "Недостаточно денег для оказания услуги"; // обновим счет GlobalDb.GlobalBase.AddToAmount(data.CurrentUserId, 0 - sum); pBxReturnBack.Enabled = false; } } // // заменим обработчик событий data.drivers.ReceivedResponse += reciveResponse; if (data.serv.price == 0) { // может быть цена нулевая - и это демо режим - можно сразу без денег работать AmountServiceText.ForeColor = System.Drawing.Color.Green; pBxGiveOxigen.Enabled = true; data.log.Write(LogMessageType.Information, "WAIT BILL: работаем в демо режиме."); } else if (Globals.ClientConfiguration.Settings.offHardware == 0) { // перейдем в режим ожидания купюр if (data.drivers.CCNETDriver.NoConnectBill == false) { data.drivers.CCNETDriver.WaitBillEscrow(); data.log.Write(LogMessageType.Information, "WAIT BILL: запускаем режим ожидания купюр."); } // при старте сканер разбудим, если не отключена возможность оплаты чеком if (Globals.ClientConfiguration.Settings.offCheck != 1) { data.drivers.scaner.Request(ZebexCommandEnum.wakeUp); data.log.Write(LogMessageType.Information, "WAIT CHECK: запускаем режим ожидания чеков."); } } }
static void Main(string[] args) { GifImage gifImage = GifDecoder.Decode(@"C:\Users\Laurie\Pictures\fillpink.gif"); ColorRGB[] globalPalette = ColorRGB.MakePalette(gifImage.GlobalColorTable); GifCube cube = new GifCube(); byte sliceT = 0; foreach (GifFrame f in gifImage.Frames) { byte[] colorTableBytes = f.LocalColorTable; ColorRGB[] palette; if (colorTableBytes == null) { palette = globalPalette; } else { palette = ColorRGB.MakePalette(colorTableBytes); } AddFrame(cube, sliceT, f.IndexedPixel, gifImage.Width, palette); } GifScriptState scriptState = new GifScriptState(); scriptState.Init(cube); scriptState.Tick(); GifCube output = scriptState.GetOutputCube(); Bitmap bmp = new Bitmap(256, 256, PixelFormat.Format24bppRgb); Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, bmp.PixelFormat); // Declare an array to hold the bytes of the bitmap. int numBytes = Math.Abs(bmpData.Stride) * bmp.Height; byte[] rgbValues = new byte[numBytes]; int Idx = 0; for (int X = 0; X < 256; X++) { for (int Y = 0; Y < 256; Y++) { ColorRGB col = output[new ColorRGB((byte)X, (byte)Y, 0)]; rgbValues[Idx++] = col.R; rgbValues[Idx++] = col.G; rgbValues[Idx++] = col.B; } } // Copy the RGB values back to the bitmap System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, bmpData.Scan0, numBytes); // Unlock the bits. bmp.UnlockBits(bmpData); bmp.Save(@"C:\Users\Laurie\Pictures\fillpinkOUT.gif", ImageFormat.Gif); /* * Color32[] pallette = new OcTreeQuantizer(8).Quantizer(bmp); * GifHelper.Quantizer(bmp, pallette); * * GifImage resultImage = new GifImage * { * Frames = new List<GifFrame>() * { * new GifFrame() { * Image = bmp, * ImageDescriptor = new ImageDescriptor * { * LctFlag = false,//true, * LctSize = pallette.Length, * Width = 256, * Height = 256, * } * } * }, * LogicalScreenDescriptor = new LogicalScreenDescriptor * { * Width = 256, * Height = 256, * } * }; * GifEncoder.Encode(resultImage, @"C:\Users\Laurie\Pictures\fillpinkOUT.gif");*/ }
/// <summary> /// Loads a GIF file from the given path, and displays the resulting frames. /// </summary> /// <param name="path">The path to load the GIF file from.</param> private void LoadGif(string path) { FramesDisplayPanel.SuspendLayout(); // Remove current panels. foreach (GifControl gc in FramesDisplayPanel.Controls) gc.Dispose(); FramesDisplayPanel.Controls.Clear(); GifImage<BitmapFrame> gifImage = null; try { using (FileStream gifStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) gifImage = new GifImage<BitmapFrame>(gifStream, BitmapFrame.FromBuffer, BitmapFrame.AllowableBitDepths); } catch (Exception) { // Couldn't load GIF, don't display. ImageInfo.Text = "Unable to load gif."; FramesDisplayPanel.ResumeLayout(); return; } ImageInfo.Text = "Duration: {0:0.00s} Iterations: {1} Size: {2}".FormatWith( TimeSpan.FromMilliseconds(gifImage.Duration).TotalSeconds, gifImage.Iterations, gifImage.Size); var frames = gifImage.Frames; for (int i = 0; i < frames.Length; i++) { string info = "{0}: {1}ms".FormatWith(i + 1, frames[i].Duration); GifControl gc = new GifControl(frames[i], info); FramesDisplayPanel.Controls.Add(gc); } FramesDisplayPanel.ResumeLayout(); }
public void AddItem(GifImage image, Tuple <int, int> cell) { m_items.Add(image, cell); }
public Energizer() { form.SetBounds(0, 0, 1280, 750); var menuStrip = new MenuStrip(); menuStrip.BackColor = Color.Gold; menuStrip.Name = "File"; menuStrip.Text = "File"; menuStrip.Items.Add(newGame); var menu1 = new ToolStripMenuItem(); menuStrip.Items.Add(menu1); menu1.Name = "menu1"; menu1.Text = "File"; menu1.ForeColor = Color.Black; menu1.BackColor = Color.Yellow; menu1.DropDownItems.Add(newGame); newGame.Name = "menu1"; newGame.Text = "New Game"; newGame.Click += startNew; menu1.DropDownItems.Add(quit); quit.Name = "submenu"; quit.Text = "Quit"; quit.Click += quitGame; form.Controls.Add(menuStrip); panel.SetBounds(0, 0, 1280, 750); panel.BackColor = Color.Red; form.Controls.Add(panel); g = panel.CreateGraphics(); energy = Image.FromFile(Environment.CurrentDirectory + "\\energy.png"); monster = Image.FromFile(Environment.CurrentDirectory + "\\monster.png"); monsterFollow = Image.FromFile(Environment.CurrentDirectory + "\\monsterFollow.png"); shipleft = new GifImage(Environment.CurrentDirectory + "\\shipleft.gif"); shipright = new GifImage(Environment.CurrentDirectory + "\\shipright.gif"); shipup = new GifImage(Environment.CurrentDirectory + "\\shipup.gif"); shipdown = new GifImage(Environment.CurrentDirectory + "\\shipdown.gif"); explosion = Image.FromFile(Environment.CurrentDirectory + "\\explosion.png"); bulletOne = Image.FromFile(Environment.CurrentDirectory + "\\bulletOne.png"); bulletTwo = Image.FromFile(Environment.CurrentDirectory + "\\bulletTwo.png"); bulletThree = Image.FromFile(Environment.CurrentDirectory + "\\bulletThree.png"); bulletFour = Image.FromFile(Environment.CurrentDirectory + "\\bulletFour.png"); submarineLeftUp = Image.FromFile(Environment.CurrentDirectory + "\\submarineLeftUp.png"); submarineLeftDown = Image.FromFile(Environment.CurrentDirectory + "\\submarineLeftDown.png"); submarineTopLeft = Image.FromFile(Environment.CurrentDirectory + "\\submarineTopLeft.png"); submarineTopRight = Image.FromFile(Environment.CurrentDirectory + "\\submarineTopRight.png"); submarineRightUp = Image.FromFile(Environment.CurrentDirectory + "\\submarineRightUp.png"); submarineRightDown = Image.FromFile(Environment.CurrentDirectory + "\\submarineRightDown.png"); submarineBottomLeft = Image.FromFile(Environment.CurrentDirectory + "\\submarineBottomLeft.png"); submarineBottomRight = Image.FromFile(Environment.CurrentDirectory + "\\submarineBottomRight.png"); ship = new Ship(); ship.x = 5; ship.y = 4; ship.direction = "right"; }
/// <summary> /// Loads a GIF file from the given path, and displays the resulting frames. /// </summary> /// <param name="path">The path to load the GIF file from.</param> private void LoadGif(string path) { FramesDisplayPanel.SuspendLayout(); // Remove current panels. foreach (GifControl gc in FramesDisplayPanel.Controls) gc.Dispose(); FramesDisplayPanel.Controls.Clear(); GifImage<BitmapFrame> gifImage = null; try { using (FileStream gifStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) gifImage = new GifImage<BitmapFrame>(gifStream, BitmapFrame.FromBuffer, BitmapFrame.AllowableBitDepths); } catch (Exception) { // Couldn't load GIF, don't display. ImageInfo.Text = "Unable to load gif."; FramesDisplayPanel.ResumeLayout(); return; } ImageInfo.Text = string.Format(CultureInfo.CurrentCulture, "Iterations: {0} Size: {1}", gifImage.Iterations, gifImage.Size); ImmutableArray<GifFrame<BitmapFrame>> frames = gifImage.Frames; for (int i = 0; i < frames.Length; i++) { string info = string.Format(CultureInfo.CurrentCulture, "{0}: {1}ms", i + 1, frames[i].Duration); GifControl gc = new GifControl(frames[i], info); FramesDisplayPanel.Controls.Add(gc); } FramesDisplayPanel.ResumeLayout(); }
/// <summary> /// Gif动画单色化 /// </summary> /// <param name="gifFilePath">原动画路径</param> /// <param name="outputPath">单色后动画路径</param> public static void Monochrome(string gifFilePath, string outputPath) { if (!File.Exists(gifFilePath)) { throw new IOException(string.Format("文件{0}不存在!", gifFilePath)); } using (Bitmap ora_Img = new Bitmap(gifFilePath)) { if (ora_Img.RawFormat.Guid != ImageFormat.Gif.Guid) { throw new IOException(string.Format("文件{0}!", gifFilePath)); } } GifImage gifImage = GifDecoder.Decode(gifFilePath); int transIndex = gifImage.LogicalScreenDescriptor.BgColorIndex; int c1 = (255 << 24) | (158 << 16) | (128 << 8) | 128; int c2 = (255 << 24) | (0 << 16) | (0 << 8) | 0; int c3 = (255 << 24) | (255 << 16) | (255 << 8) | 255; int c4 = (255 << 24) | (0 << 16) | (0 << 8) | 0; int[] palette = new int[] { c1, c2, c3, c4 }; byte[] buffer = new byte[12] { 128, 128, 128, 0, 0, 0, 255, 255, 255, 0, 0, 0 }; gifImage.GlobalColorTable = buffer; gifImage.LogicalScreenDescriptor.BgColorIndex = 0; gifImage.LogicalScreenDescriptor.GlobalColorTableSize = 4; gifImage.LogicalScreenDescriptor.GlobalColorTableFlag = true; int index = 0; foreach (GifFrame f in gifImage.Frames) { Color32[] act = PaletteHelper.GetColor32s(f.LocalColorTable); f.LocalColorTable = buffer; Color bgC = act[(transIndex / 3)].Color; byte bgGray = (byte)(bgC.R * 0.3 + bgC.G * 0.59 + bgC.B * 0.11); BitmapData bmpData = f.Image.LockBits(new Rectangle(0, 0, f.Image.Width, f.Image.Height), ImageLockMode.ReadWrite, f.Image.PixelFormat); unsafe { int *p = (int *)bmpData.Scan0.ToPointer(); for (int i = 0; i < f.Image.Width * f.Image.Height; i++) { if (p[i] == 0) { p[i] = c1; } else { Color c = Color.FromArgb(p[i]); int gray = (byte)(c.R * 0.3 + c.G * 0.59 + c.B * 0.11); if (gray > bgGray) { if (bgGray > 128) { p[i] = c2; } else { p[i] = c3; } } else if (gray < bgGray) { if (bgGray > 128) { p[i] = c3; } else { p[i] = c2; } } else { p[i] = c1; } } } } f.Image.UnlockBits(bmpData); f.GraphicExtension.TranIndex = 0; f.ColorDepth = 2; f.ImageDescriptor.LctFlag = false; index++; } GifEncoder.Encode(gifImage, outputPath); }
/// <summary> /// Raised when a new index is selected from ImageSelector. /// Loads the GIF file of that filename. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The event data.</param> private void ImageSelector_SelectedIndexChanged(object sender, EventArgs e) { if (!SavePrompt()) return; loaded = false; changed = false; filePath = Path.Combine(filesPath, (string)ImageSelector.Items[ImageSelector.SelectedIndex]); if (gifImage != null) foreach (GifFrame<Bitmap> frame in gifImage.Frames) frame.Image.Dispose(); if (desiredFrames != null) foreach (Bitmap frame in desiredFrames) frame.Dispose(); gifImage = null; frameIndex = -1; desiredFrames = null; ImageComparison.Panel1.BackgroundImage = null; ImageComparison.Panel2.BackgroundImage = null; ImageSourceColor.BackColor = Color.Transparent; ImageDesiredColor.BackColor = Color.Transparent; ImageSourcePalette.BackColor = PaletteControls.BackColor; ImageDesiredPalette.BackColor = PaletteControls.BackColor; ImageSourcePalette.Controls.Clear(); ImageDesiredPalette.Controls.Clear(); foreach (Panel panel in sourceSwatches) panel.Dispose(); foreach (Panel panel in desiredSwatches) panel.Dispose(); sourceSwatches.Clear(); desiredSwatches.Clear(); SourceAlphaCode.ResetText(); SourceColorCode.ResetText(); DesiredAlphaCode.ResetText(); DesiredColorCode.ResetText(); FrameControls.Enabled = false; PaletteControls.Enabled = false; ColorControls.Enabled = false; ErrorLabel.Visible = false; currentColor = Color.Empty; FileStream gifStream = null; try { gifStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); gifImage = GifImage.OfBitmap(gifStream); } catch (Exception) { Console.WriteLine("An error occurred attempting to load the file: " + filePath); ShowError("An error occurred attempting to load this file."); return; } finally { if (gifStream != null) gifStream.Dispose(); } Indexer.UseTimingsFrom(gifImage); AlphaRemappingTable map = new AlphaRemappingTable(); string mapFile = Path.ChangeExtension(filePath, AlphaRemappingTable.FileExtension); if (File.Exists(mapFile)) map.LoadMap(mapFile); colorMappingTable.Clear(); foreach (var frame in gifImage.Frames) BuildColorMap(frame.GetColorTable(), map); sourceSwatches.Capacity = colorMappingTable.Count; desiredSwatches.Capacity = colorMappingTable.Count; int swatchSize = ImageSourcePalette.Height - 2; Size size = new Size(swatchSize, swatchSize); Point location = new Point(1, 1); ImageSourcePalette.SuspendLayout(); ImageDesiredPalette.SuspendLayout(); int mappingIndex = 0; foreach (var colorMapping in colorMappingTable) { Panel sourcePanel = new Panel() { Size = size, Location = location }; Panel desiredPanel = new Panel() { Size = size, Location = location }; sourcePanel.Tag = desiredPanel; desiredPanel.Tag = sourcePanel; sourceSwatches.Add(sourcePanel); desiredSwatches.Add(desiredPanel); ImageSourcePalette.Controls.Add(sourcePanel); ImageDesiredPalette.Controls.Add(desiredPanel); sourceSwatches[mappingIndex].Click += Swatch_Clicked; desiredSwatches[mappingIndex].Click += Swatch_Clicked; sourceSwatches[mappingIndex].BackColor = colorMapping.Key; desiredSwatches[mappingIndex].BackColor = colorMapping.Value; if (mappingIndex == 0) currentColor = colorMapping.Key; mappingIndex++; location.X += swatchSize + 1; } location.Y = 0; Panel blankSourcePanel = new Panel() { Size = ImageSourcePalette.Size, Location = location, BackColor = SystemColors.Control }; ImageSourcePalette.Controls.Add(blankSourcePanel); Panel blankDesiredPanel = new Panel() { Size = ImageDesiredPalette.Size, Location = location, BackColor = SystemColors.Control }; ImageDesiredPalette.Controls.Add(blankDesiredPanel); ImageSourcePalette.ResumeLayout(); ImageDesiredPalette.ResumeLayout(); ImageSourcePalette.BackColor = ImageComparison.BackColor; ImageDesiredPalette.BackColor = ImageComparison.BackColor; desiredFrames = new Bitmap[gifImage.Frames.Length]; for (int i = 0; i < desiredFrames.Length; i++) desiredFrames[i] = (Bitmap)gifImage.Frames[i].Image.Clone(); UpdateDesiredFrames(); FrameControls.Enabled = true; PaletteControls.Enabled = true; ColorControls.Enabled = true; SaveCommand.Enabled = true; UpdateSelectedFrame(0); UpdateColorHex(); UpdateColorDisplay(); loaded = true; }
/// <summary> /// 合并多个gif文件 /// </summary> /// <param name="sourceGifs">原图像路径集合</param> /// <param name="outGif">合并后图像路径</param> /// <param name="delay">间隔时间</param> /// <param name="repeat">是否重复播放</param> public static void Merge(List <string> sourceGifs, string outGif, short delay, bool repeat) { GifImage gifImage = null; int index = 0; short lastDelay = delay; foreach (string source in sourceGifs) { if (!File.Exists(source)) { throw new IOException(string.Format("文件{0}不存在!", source)); } using (Bitmap ora_Img = new Bitmap(source)) { if (ora_Img.RawFormat.Guid != ImageFormat.Gif.Guid) { throw new IOException(string.Format("文件{0}!", source)); } } GifImage gif = GifDecoder.Decode(source); if (index == 0) { gifImage = gif; } int frameCount = 0; foreach (GifFrame f in gif.Frames) { if (frameCount == 0 && f.GraphicExtension.DisposalMethod == 0) { f.GraphicExtension.DisposalMethod = 2; } if (!f.ImageDescriptor.LctFlag) { f.ImageDescriptor.LctSize = f.LocalColorTable.Length / 3; f.ImageDescriptor.LctFlag = true; f.GraphicExtension.TranIndex = gif.LogicalScreenDescriptor.BgColorIndex; f.LocalColorTable = gif.GlobalColorTable; } if (frameCount == 0) { f.Delay = f.GraphicExtension.Delay = lastDelay; } if (f.Delay == 0) { f.Delay = f.GraphicExtension.Delay = lastDelay; } f.ColorDepth = (byte)(Math.Log(f.ImageDescriptor.LctSize, 2)); lastDelay = f.GraphicExtension.Delay; frameCount++; } gifImage.Frames.AddRange(gif.Frames); index++; } if (repeat && gifImage.ApplictionExtensions.Count == 0) { ApplicationEx ae = new ApplicationEx(); gifImage.ApplictionExtensions.Add(ae); } gifImage.LogicalScreenDescriptor.PixcelAspect = 0; Size maxSize = FindMaxSize(sourceGifs); gifImage.LogicalScreenDescriptor.Width = (short)maxSize.Width; gifImage.LogicalScreenDescriptor.Height = (short)maxSize.Height; GifEncoder.Encode(gifImage, outGif); }