How to save Image from remote URL, How to save image of Dropbox URL, How to check Image extension is Valid or not, How to check remote URL is valid or not using c# asp.net

In this blog I am going to explain how to save Image from remote URL in your Drive, how to save image of Dropbox URL which is little bit different and few small things like how to check Image extension is Valid or not and how we could check whether remote URL is valid or not using c# asp.net. Apart from these things small things are also there which I have used in this code like how to removes empty elements from an array using LINQ and how to remove special character like semi-colon from elements of array if exists using LINQ. Lot of things are here explained in a very simple and easy to understand way.

Paste all code as it is in your new selected project without any changes. Add Drawing referance and few below specified namespaces and don't forget to add Image folder in your base directory and run your code. you will get the result without any error... So, enjoy coding... :)
using System.Drawing;
using System.Diagnostics;
using System.Net;
using System.IO;

namespace UploadImage
{
    class Program
    {
        static void Main(string[] args)
        {
            UploadImage();
        }

        private static void UploadImage()
        {
            string sPathToStoreImages = System.IO.Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory) + "\\Images\\";               /* Gets the base path of the Project i.e Bin/Debug/Images of your project. create a folder in this path- Images*/
            Stopwatch sw = new Stopwatch();

            /* Here we are taking different types of url links */
            string[] sImages = { "https://lh3.googleusercontent.com/-21H14jVdbLI/VWLCTrQwscI/AAAAAAAAAH8/cpYz__D-fcs/s512/3.jpg;",
                                 "http://www.functionx.com/vcsharp/bitmaps/resources/flying.bmp;",
                                 "http://img5a.flixcart.com/image/shoe/f/s/q/white-alr-zapatoz-7-original-imadyge58ksxhsej.jpeg;",
                                 "http://i304.photobucket.com/albums/nn200/jain1priyanka/img_5602-800x1200_zpslfzdq7pn.jpg",
                                 "https://www.dropbox.com/s/lad035b0fs5dogt/TestDropbox.bmp?dl=0","" };

            sImages = sImages.Where(x => !string.IsNullOrEmpty(x)).ToArray();  /* Removes empty elements from array */
            sImages = sImages.Select(s => s.Trim(';')).ToArray();              /* Removes special character- semi-colon from elements of array if exists */

            if (sImages != null)
            {
                sw.Start();
                SaveImageToLocalDrive(ref sImages, ref sPathToStoreImages);
                sw.Stop();
                Console.WriteLine(sw.Elapsed);
                Console.ReadKey();
            }
        }

        private static void SaveImageToLocalDrive(ref string[] sImageLink, ref string sPathToStoreImages)
        {
            string sImageUri = string.Empty;
            List<string> listError = new List<string>();
            int iCount = 1;
            try
            {
                foreach (var ImageToUpload in sImageLink)
                {
                    if (ImageToUpload.Length > 0)
                    {
                        if (ImageToUpload.Contains("?dl=0"))                                /* This if blocks checks for dropbox image url because dropbox images can't be downloaded with ?dl=0 at the end, it has to be replaced with ?dl=1 */
                        {
                            sImageUri = ImageToUpload.Replace("?dl=0", "?dl=1");
                        }
                        else
                        {
                            sImageUri = ImageToUpload;
                        }
                        if (IsImageFormatValid(sImageUri))
                        {
                            try
                            {
                                WebRequest wrImg = HttpWebRequest.Create(sImageUri);
                                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(wrImg.RequestUri);
                                HttpWebResponse response = null;

                                if (RemoteFileExists(ref req, ref response))              /* This If block checks wehether the url given is valid or not.*/
                                {
                                    Stream streamImg = response.GetResponseStream();
                                    Image img = Image.FromStream(streamImg);
                                    wrImg.Abort();
                                    req.Abort();
                                    streamImg.Close();
                                    response.Close();

                                    /*Below we are checking Image dimension & resolution, if it satisfies the requirement then only we proceed futher*/
                                    int imgResolution = (int)img.HorizontalResolution;
                                    int imgHeight = img.Height;
                                    int imgWidth = img.Width;
                                   Int64 iImageSize = response.ContentLength;              /* Checks image size, we are ignoring images having size more than 3 MB */

                                    if ((Convert.ToInt32(imgWidth) < 762) || (Convert.ToInt32(imgHeight) < 1100) || (Convert.ToInt32(imgResolution) < 72) || iImageSize > 3000000)
                                    {
                                        Console.WriteLine("Image resolution or size not compatible for this link: " + ImageToUpload);
                                    }
                                    else
                                    {
                                        /* This method saves the image from the url to specified folder path if url passes through all check-points*/
                                        ProcessImage(sImageUri, sPathToStoreImages, ref img, iCount);
                                        iCount++;                                        /* After processing of each image, incrementing count by 1*/
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("ImageToUpload URL seems Invalid");
                                }
                            }

                            catch (NotSupportedException Nex)
                            {
                                Console.WriteLine("Error occured in SaveImageToLocalDrive. " + Nex.Message);
                            }
                            catch (WebException wex)
                            {
                                Console.WriteLine("Error occured in SaveImageToLocalDrive. " + wex.Message);
                            }
                            catch (ProtocolViolationException IPex)
                            {
                                Console.WriteLine("Error occured in SaveImageToLocalDrive. " + IPex.Message);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Error occured in SaveImageToLocalDrive. " + ex.Message);
                            }
                        }
                        else
                        {
                            Console.WriteLine("ImageToUpload extension is not found to be any of these types: .jpg/ .png/ .bmp/ .jpeg/ .gif.");
                        }
                    }
                    else
                    {
                        Console.WriteLine("ImageToUpload Length is found to be zero or less.");
                    }
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private static void ProcessImage(string sImageUri, string sPathToStoreImages, ref Image img, int iCount)
        {
            List<string> listError = new List<string>();
            String strFileNameWithoutExtension = String.Empty;
            String strFileExtension = String.Empty;

            string strFileNameWithPath = string.Empty;

            string remoteImageUrl = sImageUri.ToString();
            try
            {
                strFileNameWithoutExtension = Path.GetFileName(remoteImageUrl);
                strFileExtension = Path.GetExtension(remoteImageUrl);
                strFileNameWithoutExtension = "Image_" + iCount;                                                      /* Renaming Images Here with "Image" as prefix and count number as suffix*/
                DirectoryInfo diFileCheck = new DirectoryInfo(@"" + sPathToStoreImages);
                FileInfo[] fiFiles = diFileCheck.GetFiles();


                if (strFileExtension != "" && strFileExtension.Contains("?dl=1"))                                     /* For Dropbox URl, trims "?dl=1 and saves image with valid extension Only"*/
                {
                    strFileNameWithPath = @"" + sPathToStoreImages + strFileNameWithoutExtension + strFileExtension.Substring(0, strFileExtension.LastIndexOf("?dl=1") + 0); ;
                }
                else if (strFileExtension != "")                                                                      /* If any extension exists for Image which we are getting above then add extension */
                {
                    strFileNameWithPath = @"" + sPathToStoreImages + strFileNameWithoutExtension + strFileExtension;
                }

                else
                {
                    strFileNameWithPath = @"" + sPathToStoreImages + strFileNameWithoutExtension + ".png";            /* If url doesn't have any extension for Image then by forcely I am saving here with .png extension */
                }
                img.Save(strFileNameWithPath);
                img.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error occured in ProcessImage method of UploadImageToSharedDrive. " + ex.Message);
            }
        }


        /* This method checks for specified extension, returns true if image extension matches or else it returns false */
        public static bool IsImageFormatValid(string filePath)
        {
            string[] strValidFileTypes = { "jpg", "png", "bmp", "jpeg", "gif", "" };
            string sExt = Path.GetExtension(filePath);

            /* In case of dropbox url, below If condition will work */
            if (sExt.Contains("?dl=0") || sExt.Contains("?dl=1"))
            {
                sExt = sExt.Substring(0, sExt.LastIndexOf("?dl=1") + 0);
            }
            for (int i = 0; i < strValidFileTypes.Length; i++)
            {
                if (sExt == "." + strValidFileTypes[i] || sExt == "")
                {
                    return true;
                }
            }
            return false;
        }

        /* This method checks for request, returns true if URL is valid and request returns True or else it returns false */
        public static bool RemoteFileExists(ref HttpWebRequest req, ref  HttpWebResponse response)
        {
            try
            {
                response = req.GetResponse() as HttpWebResponse;
                var result = (response.StatusCode == HttpStatusCode.OK);
                return result;
            }
            catch
            {
                return false;
            }
        }
     
    }
}

Result: Below is the output you will get on your console window and 5 images saved in your local disk::



Comments

Popular posts from this blog

Search data in Gridview on Textbox Key press event using JQuery in Asp.Net- C#

StateCode and StatusCode Values for mostly used entities in Microsoft Dynamics CRM 2013

Dumps for Microsoft Dynamics CRM MB2-703 Practice Exam Questions Free

How to import CSV files into DataTable in C#

How to show enlarge image when mouse hover on image or link in Asp.Net(c#) using JavaScript

go to top image