Question How can I convert images to gif types real gif types images using memory stream ?

chocolade

New member
Joined
Dec 15, 2020
Messages
2
Programming Experience
3-5
I'm downloading the images as jpg's but even if I will try to download them as .gif it will not be gif really gif.
I will have to open the images in paint and save them one by one as gif type.

I want in the script in the completed even to convert the array of images to gif's. To do it after this line :

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

To convert them to gif's without losing quality.

This is the complete code :

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 = "https://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 = "https://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;
            }
        }
    }
}
 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,451
Location
Sydney, Australia
Programming Experience
10+
In future, please post the relevant code only. If we have to trawl through loads of code unrelated to the issue then it makes it that much harder for us to identify the issue. That means that we may not be able to do so or we may not be inclined to do so. Either way, you lose. Do all you can to help us help you.
 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,451
Location
Sydney, Australia
Programming Experience
10+
You can't download something as a type it isn't. If an image isn't a GIF then you can't download it as a GIF. Putting a ".gif" extension on a file doesn't magically make it a GIF file, any more than slapping a label that says "Sugar" onto a jar of salt would make it taste good if you poured it into your coffee. If you want to change the format of an image file then you have to actually read the data of the file and then save it out in the new format. In its simplest form, that would look like this:
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);
}
That will actually output a file if GIF format, with a ".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.
 
Top Bottom