如何使用内存流将图像转换为gif类型真正的gif类型图像?

巧克力

新成员
已加入
2020年12月15日
留言内容
2
编程经验
3-5
我正在将图像下载为jpg,但即使我尝试将其下载为.gif,也不会是gif真正的gif。
我将不得不打开绘画中的图像并将它们一一保存为gif类型。

我想要在完成的脚本中甚至将图像数组转换为gif。在此行之后执行此操作:

C#:
images = Directory.GetFiles(@"d:\satimages", "*.jpg");

将它们转换为gif而不损失质量。

这是完整的代码:

C#:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using HtmlAgilityPack;
using unfreez_wrapper;
 
namespace SatImages
{
    public partial class Form1 : Form
    {
        private int counter = 0;
        private System.Windows.Forms.Timer moveTimer;
        private string[] images;
 
        public Form1()
        {
            InitializeComponent();
 
            moveTimer = new System.Windows.Forms.Timer();
 
            progressBar1.Value = 0;
            progressBar1.Maximum = 10;
 
            backgroundWorker1.RunWorkerAsync();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
 
        }
 
        private void Download()
        {
            var wc = new WebClient();
            wc.BaseAddress = "//en.sat24.com/en/tu/infraPolair";
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
 
            var temp = wc.DownloadData("/en");
            doc.Load(new MemoryStream(temp));
 
            var secTokenScript = doc.DocumentNode.Descendants()
                .Where(e =>
                       String.Compare(e.Name, "script", true) == 0 &&
                       String.Compare(e.ParentNode.Name, "div", true) == 0 &&
                       e.InnerText.Length > 0 &&
                       e.InnerText.Trim().StartsWith("var region")
                      ).FirstOrDefault().InnerText;
            var securityToken = secTokenScript;
            securityToken = securityToken.Substring(0, securityToken.IndexOf("arrayImageTimes.push"));
            securityToken = secTokenScript.Substring(securityToken.Length).Replace("arrayImageTimes.push('", "").Replace("')", "");
            var dates = securityToken.Trim().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            var scriptDates = dates.Select(x => new ScriptDate { DateString = x });
            foreach (var date in scriptDates)
            {
                string img = "//en.sat24.com/image?type=infraPolair&region=tu&timestamp=" + date.DateString;
 
                Image image = DownloadImageFromUrl(img);
                image.Save(@"d:\satimages\" + counter + ".jpg");
 
                counter++;
            }
        }
 
        public class ScriptDate
        {
            public string DateString { get; set; }
            public int Year
            {
                get
                {
                    return Convert.ToInt32(this.DateString.Substring(0, 4));
                }
            }
            public int Month
            {
                get
                {
                    return Convert.ToInt32(this.DateString.Substring(4, 2));
                }
            }
            public int Day
            {
                get
                {
                    return Convert.ToInt32(this.DateString.Substring(6, 2));
                }
            }
            public int Hours
            {
                get
                {
                    return Convert.ToInt32(this.DateString.Substring(8, 2));
                }
            }
            public int Minutes
            {
                get
                {
                    return Convert.ToInt32(this.DateString.Substring(10, 2));
                }
            }
        }
 
        public System.Drawing.Image DownloadImageFromUrl(string imageUrl)
        {
            System.Drawing.Image image = null;
 
            try
            {
                System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageUrl);
                webRequest.AllowWriteStreamBuffering = true;
                webRequest.Timeout = 30000;
 
                System.Net.WebResponse webResponse = webRequest.GetResponse();
 
                System.IO.Stream stream = webResponse.GetResponseStream();
 
                image = System.Drawing.Image.FromStream(stream);
 
                webResponse.Close();
            }
            catch (Exception ex)
            {
                return null;
            }
 
            return image;
        }
 
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            Download();
            backgroundWorker1.ReportProgress(counter);
        }
 
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
        }
 
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            images = Directory.GetFiles(@"d:\satimages", "*.jpg");
            unfreez_wrapper.UnFreezWrapper uw = new UnFreezWrapper();
            uw.MakeGIF(images.ToList(), @"d:\satimages\anim.gif", 8, true);
 
            moveTimer.Interval = 1000;
            moveTimer.Tick += new EventHandler(moveTimer_Tick);
            moveTimer.Start();
        }
 
 
        int imgc = 0;
        private void moveTimer_Tick(object sender, System.EventArgs e)
        {
            var image = Image.FromFile(images[imgc]);
            pictureBox1.Image = image;
 
            if (imgc < images.Length - 1)
            {
                imgc = imgc + 1;
            }
            else
            {
                imgc = 0;
            }
        }
    }
}
 

金西尼

C#论坛主持人
工作人员
已加入
2011年4月23日
留言内容
3,501
地点
悉尼,澳大利亚
编程经验
10+
将来,请仅发布相关代码。如果我们必须遍历与问题无关的代码负载,那么这将使我们很难识别问题。这意味着我们可能无法这样做,或者我们可能不愿意这样做。不管怎样,你输了。竭尽所能帮助我们为您提供帮助。
 

金西尼

C#论坛主持人
工作人员
已加入
2011年4月23日
留言内容
3,501
地点
悉尼,澳大利亚
编程经验
10+
您不能下载某种不是的东西。如果图像不是GIF,则无法将其下载为GIF。放一个".gif"文件扩展名并不能神奇地使它成为GIF文件,只不过是拍打标签"Sugar"如果将其倒入一罐盐中,则它的味道会很好。如果要更改图像文件的格式,则必须实际读取文件的数据,然后将其保存为新格式。最简单的形式如下所示:
C#:
var sourceImagePath = "source JPG file path here";

using (var img = Image.FromFile(sourceImagePath))
{
    var destinationImagePath = Path.ChangeExtension(sourceImagePath, "gif");

    img.Save(destinationImagePath, ImageFormat.Gif);
}
如果使用GIF格式,实际上会输出一个文件".gif" extension. I'm not sure exactly what quality you'd get in that specific case. If it's not acceptable, you can check the documentation for the Image.Save method and see what overloads are available and what options are available for specifying quality. This is not something I've done much of so I'll leave the experimentation and testing to you.
 
最佳 底部