//原圖路徑 string imgPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\0.gif"; //原圖 Image img = Image.FromFile(imgPath); //不夠100*100的不縮放 if (img.Width > 100 && img.Height > 100) { //新圖第一幀 Image new_img = new Bitmap(100, 100); //新圖其他幀 Image new_imgs = new Bitmap(100, 100); //新圖第一幀GDI+繪圖對象 Graphics g_new_img = Graphics.FromImage(new_img); //新圖其他幀GDI+繪圖對象 Graphics g_new_imgs = Graphics.FromImage(new_imgs); //配置新圖第一幀GDI+繪圖對象 g_new_img.CompositingMode = CompositingMode.SourceCopy; g_new_img.InterpolationMode = InterpolationMode.HighQualityBicubic; g_new_img.PixelOffsetMode = PixelOffsetMode.HighQuality; g_new_img.SmoothingMode = SmoothingMode.HighQuality; g_new_img.Clear(Color.FromKnownColor(KnownColor.Transparent)); //配置其他幀GDI+繪圖對象 g_new_imgs.CompositingMode = CompositingMode.SourceCopy; g_new_imgs.InterpolationMode = InterpolationMode.HighQualityBicubic; g_new_imgs.PixelOffsetMode = PixelOffsetMode.HighQuality; g_new_imgs.SmoothingMode = SmoothingMode.HighQuality; g_new_imgs.Clear(Color.FromKnownColor(KnownColor.Transparent)); //遍歷維數 foreach (Guid gid in img.FrameDimensionsList) { //因為是縮小GIF文件所以這裡要設置為Time //如果是TIFF這裡要設置為PAGE FrameDimension f = FrameDimension.Time; //獲取總幀數 int count = img.GetFrameCount(f); //保存標示參數 Encoder encoder = Encoder.SaveFlag; // EncoderParameters ep = null; //圖片編碼、解碼器 ImageCodecInfo ici = null; //圖片編碼、解碼器集合 ImageCodecInfo[] icis = ImageCodecInfo.GetImageDecoders(); //為 圖片編碼、解碼器 對象 賦值 foreach (ImageCodecInfo ic in icis) { if (ic.FormatID == ImageFormat.Gif.Guid) { ici = ic; break; } } //每一幀 for (int c = 0; c < count; c++) { //選擇由維度和索引指定的幀 img.SelectActiveFrame(f, c); //第一幀 if (c == 0) { //將原圖第一幀畫給新圖第一幀 g_new_img.DrawImage(img, new Rectangle(0, 0, 100, 100), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel); //把振頻和透明背景調色板等設置復制給新圖第一幀 for (int i = 0; i < img.PropertyItems.Length; i++) { new_img.SetPropertyItem(img.PropertyItems[i]); } ep = new EncoderParameters(1); //第一幀需要設置為MultiFrame ep.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.MultiFrame); //保存第一幀 new_img.Save(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"/temp/" + Path.GetFileName(imgPath), ici, ep); } //其他幀 else { //把原圖的其他幀畫給新圖的其他幀 g_new_imgs.DrawImage(img, new Rectangle(0, 0, 100, 100), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel); //把振頻和透明背景調色板等設置復制給新圖第一幀 for (int i = 0; i < img.PropertyItems.Length; i++) { new_imgs.SetPropertyItem(img.PropertyItems[i]); } ep = new EncoderParameters(1); //如果是GIF這裡設置為FrameDimensionTime //如果為TIFF則設置為FrameDimensionPage ep.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.FrameDimensionTime); //向新圖添加一幀 new_img.SaveAdd(new_imgs, ep); } } ep = new EncoderParameters(1); //關閉多幀文件流 ep.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.Flush); new_img.SaveAdd(ep); } //釋放文件 img.Dispose(); new_img.Dispose(); new_imgs.Dispose(); g_new_img.Dispose(); g_new_imgs.Dispose(); }
//效果
100*100