Exemple #1
0
        private async Task DownloadFile(ImageDetails img)
        {
            try
            {
                Uri uri = new Uri(img.ImageUrl);

                //string formatedName = string.Format("{0}_{1:yyyy_MM_dd_hh_mm_ss_fff}", img.ID, DateTime.Now);
                string formatedName = string.Format("{0}", img.ID);

                string downloadToDirectory = @"C:\Users\Abhi\Documents\hashes\" + formatedName;

                img.pathOnDisk = downloadToDirectory;

                HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(uri);
                httpWebRequest.MaximumAutomaticRedirections = 1;
                httpWebRequest.UserAgent = ImageDownLoadRequestUserAgent;
                httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

                IAsyncResult ar = httpWebRequest.BeginGetResponse(GetAsyncResponse, new object[] { httpWebRequest, formatedName });
            }
            catch (WebException we)
            {
                Debug.Print(we.Message);
                Debug.Print(we.StackTrace);
            }
            catch (Exception e)
            {
                Debug.Print(e.Message);
                Debug.Print(e.StackTrace);
            }
        }
        public ImageDetails Load(Int32 id)
        {
            sql = "SELECT * FROM " + table + " WHERE  " + table + "ID = " + id;

            db.Open();

            command.Connection = db;
            command.CommandText = sql;
            SqlCeDataReader result = command.ExecuteReader();

            ImageDetails data = new ImageDetails();
            while (result.Read())
            {
                data = new ImageDetails(
                    result.GetInt32(0),
                    result.GetString(1),
                    DateTime.Now.ToUniversalTime(),
                    result.GetSqlBinary(3).Value,
                    result.GetInt32(4),
                    result.GetInt32(5));
            }

            db.Close();

            return data;
        }
        public static FileDetails ToFileDetails(FileEntity entity)
        {
            Guard.NotNull(entity, nameof(entity));

            if (entity.Image is null)
            {
                throw new Exception("Image property must be included.");
            }

            return(new FileDetails
            {
                FileId = new FileId(entity.Id),
                Uploader = ToAppUserNames(entity.Uploader),
                DatabaseFiles = new DatabaseFiles(new Domain.FileName(entity.SourceFileName), entity.Image.ThumbnailFileName is null ? null : new FileName(entity.Image.ThumbnailFileName)),
                Title = new FileTitle(entity.Title ?? ""),
                Description = new FileDescription(entity.Description ?? ""),
                PrimaryDateTime = ToPrimaryDateTime(entity.PrimaryDateTime),
                FileSize = new DataSize(entity.SourceFileSize),
                Tags = entity.Tags?.Select(ToTag).ToArray() ?? Array.Empty <Tag>(),

                ImageDetails = new ImageDetails()
                {
                    Dimensions = GetImageDimensions(entity.Image)
                },
            });
Exemple #4
0
        //https://www.janaks.com.np/file-upload-asp-net-core-web-api/
        public async Task <ImageDetails> SaveAsync(IFormFile file)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }


            var imageDetails = new ImageDetails()
            {
                Id          = Guid.NewGuid(),
                Name        = file.FileName,
                ContentType = file.ContentType,
                Hash        = GetHash(file)
            };

            // @TODO: Check db for existing hash and just return a reference to that file if we have one
            //		  Not sure if we should still generate a new 'id' and just link back to the same file
            //		  or literally just return the existing files Id

            var uploads  = Path.Combine(_hostingEnvironment.WebRootPath, "Images");
            var filePath = Path.Combine(uploads, imageDetails.Id.ToString() + " - " + imageDetails.Name);

            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(fileStream);
            }

            return(imageDetails);
        }
        public void Test_WriteToImage_IsGood()
        {
            Int32  pageHeight = 1000;
            String path       = "";
            var    textPieces = new List <List <ImageText> >()
            {
                new List <ImageText>()
                {
                    new ImageText("The first line of text", new Font(FontFamily.GenericSansSerif, (Single)72.0, FontStyle.Bold))
                },
                new List <ImageText>()
                {
                    new ImageText("The second line of text", new Font(FontFamily.GenericSansSerif, (Single)72.0, FontStyle.Regular))
                },
                new List <ImageText>()
                {
                    new ImageText("The third line of text", new Font(FontFamily.GenericSansSerif, (Single)60.0, FontStyle.Regular))
                },
                new List <ImageText>()
                {
                    new ImageText("The fourth line of text", new Font(FontFamily.GenericSansSerif, (Single)32.0, FontStyle.Regular))
                }
            };

            ImageDetails details = new ImageDetails(path, Color.White, Color.Black, textPieces);

            var pen = new InkPen();

            pen.WriteToImage(pageHeight, details);

            Assert.NotZero(pen.LineBottom, $"Moved no distance down the page.");
        }
Exemple #6
0
        private void refreshListImage(string path, string search)
        {
            string root = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            string[] supportedExtensions = new[] { ".jpeg", ".jpg", ".tiff" };
            var      files = Directory.GetFiles(path, "*.*").Where(s => supportedExtensions.Contains(Path.GetExtension(s).ToLower()));

            wg_images.Clear();
            foreach (var file in files)
            {
                if (checkFilterAndSearch(file, search, wg_rateFilter))
                {
                    ImageDetails id = new ImageDetails()
                    {
                        Path      = file,
                        FileName  = System.IO.Path.GetFileName(file),
                        Extension = System.IO.Path.GetExtension(file),
                    };

                    BitmapImage img = new BitmapImage();
                    img.BeginInit();
                    img.CacheOption = BitmapCacheOption.OnLoad;
                    img.UriSource   = new Uri(file, UriKind.Absolute);
                    img.EndInit();
                    id.Width  = img.PixelWidth;
                    id.Height = img.PixelHeight;

                    // I couldn't find file size in BitmapImage
                    FileInfo fi = new FileInfo(file);
                    id.Size = fi.Length;
                    wg_images.Add(id);
                }
            }
        }
Exemple #7
0
        public AppUser(String email, String createdBy)
        {
            Id        = Guid.NewGuid().ToId();
            Email     = email;
            UserName  = email;
            CreatedBy = new EntityHeader()
            {
                Id   = Id,
                Text = createdBy
            };
            CreationDate = DateTime.Now.ToJSONString();

            LastUpdatedBy = new EntityHeader()
            {
                Id   = Id,
                Text = createdBy
            };

            LastUpdatedDate = DateTime.Now.ToJSONString();

            ProfileImageUrl = new ImageDetails()
            {
                Width    = 128,
                Height   = 128,
                ImageUrl = "https://bytemaster.blob.core.windows.net/userprofileimages/watermark.png",
                Id       = "b78ca749a1e64ce59df4aa100050dcc7"
            };

            Organizations = new List <EntityHeader>();
        }
Exemple #8
0
        public void GetPicturesTags(ImageDetails curentImage)
        {
            string apiKey    = "acc_0179023530ce71a";
            string apiSecret = "0b76efe4d5500a74f4dd49a699405170";
            string image     = curentImage.ImagePath;

            string basicAuthValue = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(String.Format("{0}:{1}", apiKey, apiSecret)));

            var client = new RestClient("https://api.imagga.com/v2/tags");

            client.Timeout = -1;

            var request = new RestRequest(Method.POST);

            request.AddHeader("Authorization", String.Format("Basic {0}", basicAuthValue));
            request.AddFile("image", image);

            IRestResponse response = client.Execute(request);
            Root          TagList  = JsonConvert.DeserializeObject <Root>(response.Content);

            foreach (var item in TagList.result.tags)
            {
                curentImage.Details.Add(item.tag.en, item.confidence);
            }
        }
Exemple #9
0
        public Dictionary <string, double> GetTags(ImageDetails CurrentImage)
        {
            string apiKey    = "acc_b8acaa3605b1e28";
            string apiSecret = "6dcca611850678f8cdef3d2c81121811";
            string image     = CurrentImage.ImagePath;

            string basicAuthValue = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(String.Format("{0}:{1}", apiKey, apiSecret)));

            var client = new RestClient("https://api.imagga.com/v2/tags");

            client.Timeout = -1;

            var request = new RestRequest(Method.POST);

            request.AddHeader("Authorization", String.Format("Basic {0}", basicAuthValue));
            request.AddFile("image", image);

            IRestResponse response = client.Execute(request);
            //Console.WriteLine(response.Content);
            ImaggaRoot myDeserializedClass = JsonConvert.DeserializeObject <ImaggaRoot>(response.Content);

            foreach (var item in myDeserializedClass.result.tags)
            {
                CurrentImage.Details.Add(item.tag.en, item.confidence);
            }
            return(CurrentImage.Details);
        }
Exemple #10
0
        public bool GetTags(string imgpath)
        {
            //List<string> result = new List<string>();
            ImageAnalysis dal       = new ImageAnalysis();
            ImageDetails  DrugImage = new ImageDetails(imgpath);
            bool          result    = false;

            Dictionary <string, double> listimg = dal.GetTags(DrugImage);
            List <string> option = new List <string>()
            {
                "pills", "bottle", "medicine", "medical", "pill bottle", "pill", "drug", "drugs", "cure", "prescription drug"
            };
            List <string> listresult = new List <string>();

            foreach (var item in DrugImage.Details)
            {
                if (item.Value > 69)
                {
                    if (option.Contains(item.Key))
                    {
                        result = true;
                    }
                }
            }

            /*  var listresult=from re in listimg
             *               where re.Value>70&& option.Contains(re.Key)
             *               select re.Key;*/
            //צריך לבדוק מה הkey
            //  List<string> Li = (List<string>)listresult;
            return(result);
        }
        /// <summary>
        /// Callback called when a face is detected or recognized
        /// </summary>
        /// <param name="faceRecEvent"></param>
        private void FaceRecCallback(IFaceRecognitionEvent faceRecEvent)
        {
            if (faceRecEvent.Label == "unknown person")
            {
                AudioDetails randomAudio = _audioList[_randomGenerator.Next(0, _audioList.Count - 1)];
                ImageDetails randomImage = _imageList[_randomGenerator.Next(0, _imageList.Count - 1)];
                _misty.DisplayImage(randomImage.Name, 1, null);
                _misty.PlayAudio(randomAudio.Name, 100, null);
            }
            else
            {
                _misty.DisplayImage("e_EcstacyStarryEyed.jpg", 1, null);
                _misty.PlayAudio("sEcstacy.wav", 100, null);
            }

            if (!_misty.Wait(5000))
            {
                return;
            }
            _misty.DisplayImage("e_ContentLeft.jpg", 1, null);
            if (!_misty.Wait(5000))
            {
                return;
            }
            _misty.RegisterFaceRecognitionEvent(FaceRecCallback, 0, false, null, null, null);
        }
Exemple #12
0
        /// <summary>
        /// Converts a System.Drawing.Bitmap to an ImageDetails object
        /// </summary>
        /// <param name="image">System.Drawing.Bitmap to convert</param>
        /// <returns>ImageDetails representation of the bitmap.</returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static ImageDetails ToImageDetails(this Bitmap image)
        {
            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }
            ImageDetails details = default;
            var          indexed = image.PixelFormat == PixelFormat.Format1bppIndexed ||
                                   image.PixelFormat == PixelFormat.Format4bppIndexed ||
                                   image.PixelFormat == PixelFormat.Format8bppIndexed;

            var bpp   = Image.GetPixelFormatSize(image.PixelFormat);
            var bytes = image.ToByteArray();

            var channels = indexed ? 1 : bpp / 8;

            var getRow = new Func <int, byte[]>((y) => GetScanLine(details, bytes, y));


            if (!indexed)
            {
                details = new ImageDetails(image.Width, image.Height, (uint)bpp, (uint)channels, image.HorizontalResolution, image.VerticalResolution, getRow);
            }
            else
            {
                var palette = image.Palette.Entries.Select(e => new PaletteEntry(e.A, e.R, e.G, e.B)).ToArray();
                details = new ImageDetails(image.Width, image.Height, (uint)bpp, image.HorizontalResolution, image.VerticalResolution, palette, getRow);
            }

            return(details);
        }
Exemple #13
0
        public List <ImageDetails> FetchImages(string directory)
        {
            string root = directory;

            string[] supportedExtensions = { ".bmp", ".jpeg", ".jpg", ".png", ".tiff" };
            var      files = Directory.GetFiles(Path.Combine(root, "Images"), "*.*").Where(s => supportedExtensions.Contains(Path.GetExtension(s).ToLower()));

            List <ImageDetails> images = new List <ImageDetails>();

            foreach (var file in files)
            {
                ImageDetails id = new ImageDetails
                {
                    Path      = file,
                    FileName  = Path.GetFileName(file),
                    Extension = Path.GetExtension(file)
                };

                BitmapImage img = new BitmapImage();
                img.BeginInit();
                img.CacheOption = BitmapCacheOption.OnLoad;
                img.UriSource   = new Uri(file, UriKind.Absolute);
                img.EndInit();
                id.Width  = img.PixelWidth;
                id.Height = img.PixelHeight;

                // I couldn't find file size in BitmapImage
                FileInfo fi = new FileInfo(file);
                id.Size = fi.Length;
                images.Add(id);
            }

            return(images);
        }
Exemple #14
0
        public static string GetRandomArtFromList(List <Contract_ImageDetails> list, IProvider prov)
        {
            if (list == null || list.Count == 0)
            {
                return(null);
            }
            Contract_ImageDetails art;

            if (list.Count == 1)
            {
                art = list[0];
            }
            else
            {
                Random rand = new Random();
                art = list[rand.Next(0, list.Count)];
            }
            ImageDetails details = new ImageDetails
            {
                ImageID   = art.ImageID,
                ImageType = (ImageEntityType)art.ImageType
            };

            return(details.GenArt(prov));
        }
Exemple #15
0
        //public ImagePreprocessor(Image<Bgr, byte> currImageI, Image<Bgr, byte> nextImageI)
        public ImagePreprocessor(ImageDetails curr, ImageDetails next)
        {
            this.curr = curr;
            this.next = next;

            this.CurrImageI = new Image <Bgr, byte>(curr.Title);
            this.NextImageI = new Image <Bgr, byte>(next.Title);
            //CvInvoke.Imwrite("testimages/test03.jpg", CurrImageI);

            DetectFace();
            ResizeImage();
            DetectFace();
            if ((facesArrCurr.Length > 0) && (facesArrNext.Length > 0))
            {
                MorphEnabled = true;
                FindFacialFeaturePoints();
                CreateDelaunay();
            }
            else
            {
                MorphEnabled = false;
            }
            Console.WriteLine(facesArrCurr.Length);
            Console.WriteLine(facesArrNext.Length);
            // DetectFaceInfo();
        }
        private ImageDetails SetImageDetails(string senderId, string receiverId)
        {
            var imageDetails = new ImageDetails();

            watchAesEncrypt = new Stopwatch();
            watchAesEncrypt.Start();

            var aesEncrypt        = new AESEncryption <Parameters>(SetParameters());
            var IV                = aesEncrypt.GenerateAesKeys();
            var encryptParameters = aesEncrypt.EncryptAES();

            watchAesEncrypt.Stop();
            AesEncryptTime = watchAesEncrypt.ElapsedMilliseconds;

            using (CryptoDbContext db = new CryptoDbContext())
            {
                imageDetails.SenderId   = senderId;
                imageDetails.ReceiverId = receiverId;
                imageDetails.Parameters = encryptParameters;
                imageDetails.IVAes      = IV;
                imageDetails.Image      = null;
                imageDetails.ImageId    = Guid.NewGuid().ToString();
                db.ImageDetails.Add(imageDetails);
                db.SaveChanges();
            }
            return(imageDetails);
        }
        public static ImageUploadManager UploadImage(ImageWallServiceClient client, ImageModel model, IEnumerable<string> tags, string author, double latitude, double longitude)
        {
            try {
                // Gets image buffer
                var buffer = ImageUploadHelper.GetBuffer(model.ImageStream);

                // Create hash for image
                string hash = ImageUploadHelper.GetHash(buffer);

                // Build image details
                var details = new ImageDetails() {
                    Name = System.IO.Path.GetFileName(model.Name),
                    Hash = hash,
                    Tags = new ObservableCollection<string>(tags),
                    UserId = author,
                    Created = DateTime.Now,
                    Latitude = latitude,
                    Longitude = longitude,

                    Size = buffer.Length,
                    Extension = System.IO.Path.GetExtension(model.Name)
                };

                // Begin upload with upload manager
                var manager = new ImageUploadManager(buffer, details);
                manager.BeginUploadAsync();
                return manager;
            }
            catch (Exception ex) {
                System.Diagnostics.Debug.WriteLine(ex);
                return null;
            }
        }
Exemple #18
0
        public VideoGenerator(ImageDetails imgdet1, ImageDetails imgdet2, VectorOfPointF points1, VectorOfPointF points2, int fpsUser, float alphaUser, string path)
        {
            this.destinationPath = path;
            sizeOfVid            = GetSizeOfImages(imgdet1, imgdet2);
            float      alpha = 0.0f;
            MorphImage m;

            try
            {
                videoWriter = new VideoWriter(fileName: destinationPath, fps: fpsUser, size: sizeOfVid, isColor: true);
                while (alpha < 1.0f)
                {
                    m = new MorphImage(imgdet1, imgdet2, points1, points2, alpha);
                    Image <Bgr, byte> morphedImage = m.GetMorphedImageI();
                    videoWriter.Write(morphedImage.Mat);
                    alpha += alphaUser;
                    morphedImage.Dispose();
                }
                if (videoWriter.IsOpened)
                {
                    videoWriter.Dispose();
                }
                MessageBox.Show($"Completed");
            }
            catch (Exception)
            {
                MessageBox.Show("The program has run out of memory. Try to use fewer images, a larger alpha value (0.05 - 0.1) or a lower FPS count (25)");
            }
        }
Exemple #19
0
        /// <summary>
        /// Converts the ImageSharp Image to the PictCode ImageDetails class
        /// </summary>
        /// <typeparam name="TPixel"></typeparam>
        /// <param name="image"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="Exception"></exception>
        internal static ImageDetails ToImageDetails <TPixel>(this Image <TPixel> image) where TPixel : unmanaged, IPixel <TPixel>
        {
            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }

            if (image.PixelType.BitsPerPixel < 32)
            {
                throw new Exception("Index images not really supported by ImageSharp at the moment. ");
            }

            var             configuration   = image.GetConfiguration();
            MemoryAllocator memoryAllocator = configuration.MemoryAllocator;

            Func <int, byte[]> getScanline = new Func <int, byte[]>(y => {
                var pixels     = image.GetPixelRowSpan(y);
                var pixelBytes = 4;
                using IMemoryOwner <byte> row = memoryAllocator.Allocate <byte>(pixelBytes * image.Width);
                Span <byte> rowSpan           = row.Memory.Span;
                PixelOperations <TPixel> .Instance.ToBgra32Bytes(configuration, pixels, rowSpan, pixels.Length);
                return(rowSpan.ToArray());
            });

            var imageDetails = new ImageDetails(width: image.Width,
                                                height: image.Height,
                                                bitsPerPixel: (uint)image.PixelType.BitsPerPixel,
                                                channels: 4,
                                                horizontalRes: image.Metadata.HorizontalResolution,
                                                verticalRes: image.Metadata.VerticalResolution,
                                                getScanline: getScanline);

            return(imageDetails);
        }
Exemple #20
0
        private void ExtractImageInSTAThreadContext(object imageDetails)
        {
            ImageDetails imageInfo  = (ImageDetails)imageDetails;
            Range        imageRange = imageInfo.imageRange;
            string       filePath   = imageInfo.filePath;

            try
            {
                imageRange.Copy();

                System.Windows.IDataObject data = System.Windows.Clipboard.GetDataObject();
                using (Bitmap bitmap = (Bitmap)data.GetData(typeof(System.Drawing.Bitmap)))
                {
                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath);
                    }
                    bitmap.Save(filePath);
                }
                System.Windows.Clipboard.Clear();
            }
            catch (OutOfMemoryException)
            {
                // try again
                System.Windows.Clipboard.Clear();
                ExtractImage(imageRange, filePath);
            }
        }
        public static async Task <ImageDetails> AnalyzeImageUrl(ComputerVisionClient client, string imageUrl)
        {
            var imageDetails = new ImageDetails();

            imageDetails.ImageUrl = imageUrl;

            // Creating a list that defines the features to be extracted from the image.
            List <VisualFeatureTypes> features = new List <VisualFeatureTypes>()
            {
                VisualFeatureTypes.Description,
                VisualFeatureTypes.Tags
            };

            ImageAnalysis results = await client.AnalyzeImageAsync(imageUrl, features);

            foreach (var caption in results.Description.Captions)
            {
                imageDetails.Description.Captions.Add(
                    new Caption
                {
                    Text       = caption.Text,
                    Confidence = caption.Confidence
                }
                    );
            }

            foreach (var tag in results.Tags)
            {
                imageDetails.Description.Tags.Add(
                    tag.Name
                    );
            }

            return(imageDetails);
        }
Exemple #22
0
        public void GetTags(ImageDetails CurrentImage)
        {
            //POST request using RestSharp
            string apiKey    = "acc_fb83cd5b0478486";
            string apiSecret = "d5dc3c0c6b26d4cd2ce752073d3ddd07";
            string image     = CurrentImage.ImagePath;

            string basicAuthValue = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(String.Format("{0}:{1}", apiKey, apiSecret)));

            var client = new RestClient("https://api.imagga.com/v2/tags");

            client.Timeout = -1;

            var request = new RestRequest(Method.POST);

            request.AddHeader("Authorization", String.Format("Basic {0}", basicAuthValue));
            request.AddFile("image", image);

            IRestResponse response = client.Execute(request);

            Root TagList = JsonConvert.DeserializeObject <Root>(response.Content); //deserialization for the json response

            //root->result->tags->tag->tag, confidence
            foreach (var item in TagList.result.tags)//going on all the results
            {
                CurrentImage.Details.Add(item.tag.en, item.confidence);
            }
        }
Exemple #23
0
 public ImageResult(string path, string outputLabel, double confidence, ImageDetails details)
 {
     Path        = path;
     OutputLabel = outputLabel;
     Confidence  = confidence;
     Details     = details;
     Error       = false;
 }
Exemple #24
0
 public static string GenArt(this ImageDetails im, IProvider prov)
 {
     if (im == null)
     {
         return(null);
     }
     return(prov.ConstructImageLink((int)im.ImageType, im.ImageID));
 }
Exemple #25
0
 public static string GenPoster(this ImageDetails im, IProvider prov, string fallbackimage = "plex_404V.png")
 {
     if ((im == null) || (im.ImageID == 0))
     {
         return(prov.ConstructSupportImageLink(fallbackimage));
     }
     return(prov.ConstructThumbLink((int)im.ImageType, im.ImageID));
 }
Exemple #26
0
 public static string GenArt(this ImageDetails im)
 {
     if (im == null)
     {
         return(null);
     }
     return(Helper.ConstructImageLink((int)im.ImageType, im.ImageID));
 }
        public void MakeObservationTest()
        {
            ImageDetails s = new ImageDetails((626 * 469), @"C:\Users\ezabuab\Pictures\test2.jpg");

            ImagePrep.MakeObservation(s);
            //not a real test just checking that this works
            //example shows this is not scalable unless parallel execution is enabled
        }
Exemple #28
0
        //private void GetEligibleWorkingURLs(List<ImageDetails> imgs)
        //{

        //    try
        //    {
        //        Parallel.ForEach(imgs, new ParallelOptions { MaxDegreeOfParallelism = 1 }, (img) =>
        //        {
        //            try
        //            {
        //                var request = (HttpWebRequest)WebRequest.Create(img.ImageUrl);
        //                request.Timeout = 500;
        //                request.Method = "HEAD";

        //                using (var response = (HttpWebResponse)request.GetResponse())
        //                {
        //                    if (response.StatusCode == HttpStatusCode.OK && response.ContentType.Contains("image"))
        //                    {
        //                        img.isValid = true;

        //                    }
        //                }
        //            }
        //            catch (WebException we)
        //            {
        //                Debug.Print(we.StackTrace);
        //            }
        //        });
        //    }
        //    catch (Exception eeeee)
        //    {
        //        Debug.Print(eeeee.StackTrace);
        //        throw;
        //    }


        //}

        private Task DownloadFile(ImageDetails img)
        {
            //using (WebClient wc = new WebClient())
            using (DwnldWebClient wc = new DwnldWebClient())
            {
                Uri uri = new Uri(img.ImageUrl);

                //string formatedName = string.Format("{0}_{1:yyyy_MM_dd_hh_mm_ss_fff}", img.ID, DateTime.Now);
                string formatedName = string.Format("{0}", img.ID);

                string downloadToDirectory = @"C:\Users\Abhi\Documents\hashes\" + formatedName;

                img.pathOnDisk = downloadToDirectory;

                var request = (HttpWebRequest)WebRequest.Create(uri);
                request.Timeout   = 2000;
                request.Method    = "HEAD";
                request.UserAgent = userAgent;

                try
                {
                    using (var response = (HttpWebResponse)request.GetResponse())
                    {
                        if (response.StatusCode == HttpStatusCode.OK && response.ContentType.Contains("image"))
                        {
                            return(wc.DownloadFileTaskAsync(uri, downloadToDirectory));
                        }
                        else
                        {
                            img.error = INVALID_TYPE_ERROR;
                            rejects++;
                            img.hash = EMPTY_MD5_HASH;
                            return(null);
                        }
                    }
                }
                catch (System.Net.WebException ex)
                {
                    img.error = ex.Message;
                    img.hash  = EMPTY_MD5_HASH;
                    Debug.Print(ex.Message);
                    Debug.Print(ex.StackTrace);
                    rejects++;
                    //return null;
                }
                catch (Exception ex)
                {
                    img.error = ex.Message;
                    img.hash  = EMPTY_MD5_HASH;
                    Debug.Print(ex.Message);
                    Debug.Print(ex.StackTrace);
                    rejects++;
                    //return null;
                }
                return(null);
                //return wc.DownloadFileTaskAsync(uri, downloadToDirectory);
            }
        }
Exemple #29
0
		public FileMetadata(string fullPath)
		{
			FullPath = fullPath;
            Name = Path.GetFileName(FullPath);
            imageDetails = new ImageDetails(FullPath);
            Timestamp = imageDetails.CreatedTime;
            Location = imageDetails.Location;
			UpdateTimestampMatch();
		}
Exemple #30
0
        public static IImageDetails AnalyseImageDetails(
            string path,
            ILocationManager locationManager,
            IClsNmbManager clsNmbManager,
            IFaultManager faultManager)
        {
            IImageDetails image;

            string imageName = System.IO.Path.GetFileName(path);

            string[] filenameArray = imageName.Split(extensionSeparator);

            string[] inputArray = filenameArray[0].Split(majorTick);

            if (inputArray.Length < 2 || inputArray.Length > 4)
            {
                faultManager.AddFault(
                    "Can't split into nmb and stn",
                    imageName);
            }

            string[] nmbsArray = inputArray[0].Split(minorTick);

            ILocation stn =
                locationManager.GetStn(
                    inputArray[1]);

            string year =
                inputArray.Length > 2 ?
                inputArray[2] :
                string.Empty;

            string multipleNote =
                inputArray.Length > 3 ?
                inputArray[3] :
                string.Empty;

            image =
                new ImageDetails(
                    path,
                    year,
                    stn,
                    multipleNote);

            ClsClass clss =
                ImageDetailFactory.GetCls(
                    nmbsArray.ToList(),
                    path,
                    faultManager,
                    clsNmbManager);

            image.SetClss(
                clss.Clss,
                clss.PresentNmbs);

            return(image);
        }
Exemple #31
0
 public ResultImageModel(ImageDetails img, int cardSide)
 {
     ImageId     = img.ImageId;
     OwnerName   = img.OwnerName;
     Name        = img.Name;
     Description = img.Description;
     Source      = img.Source;
     CardSide    = cardSide;
 }
Exemple #32
0
 public static string GenPoster(this ImageDetails im)
 {
     if (im == null)
     {
         return(null);
     }
     return(KodiHelper.ServerUrl(int.Parse(ServerSettings.JMMServerPort),
                                 MainWindow.PathAddressREST + "/GetThumb/" + (int)im.ImageType + "/" + im.ImageID + "/0.6667"));
 }
        private void CheckImageTag(ImageDetails imageDetails)
        {
            GroupTagsHolderService groupHolder = GroupTagsHolderService.GetGroupTagsHolder;
            TagHolders             tagHolder   = imageDetails.TagHolder;

            groupHolder.AdjustTags(tagHolder);

            tagHolder.AddTag(_allTagsSelection);
        }
        public ImageUploadManager(byte[] data, ImageDetails details)
        {
            this.data = data;
            this.detail = details;

            // Calculate number of packets to send
            this.numberOfPackets = (int)Math.Ceiling((float)this.data.Length / ImageUploadHelper.PacketSize);

            // Create client and event handles
            this.client = new ImageWallServiceClient();
            this.client.UploadImagePartCompleted += HandleUploadImagePartCompleted;
            this.client.BeginImageUploadCompleted += HandleBeginImageUploadComplete;
        }
        public string GetImgInfo(string path)
        {
            DataTable dt = new DataTable();
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            List<ImageDetails> listInfo = new List<ImageDetails>();
            string[] split = path.Split('/');
            try
            {
                using (MySqlConnection cnn = new MySqlConnection(ConnectionStrings.MySqlConnectionString()))
                {
                    cnn.Open();
                    using (var cmd = cnn.CreateCommand())
                    {
                        cmd.CommandText = @"SELECT filename, description, folder, hidden, feature FROM lockbusiness_images where filename=@filename";
                        cmd.Parameters.AddWithValue("filename", split[2]);
                        MySqlDataAdapter da = new MySqlDataAdapter(cmd);
                        da.Fill(dt);
                    }
                }

                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        ImageDetails objst = new ImageDetails();
                        objst.ImageFileName = dt.Rows[i]["filename"].ToString();
                        objst.ImageDescription = dt.Rows[i]["description"].ToString();
                        objst.ImageFolder = dt.Rows[i]["folder"].ToString();
                        objst.ImageHidden = Convert.ToInt32(dt.Rows[i]["hidden"]);
                        objst.ImageFeature = dt.Rows[i]["feature"].ToString().Replace("<br>", " \n ");
                        listInfo.Insert(i, objst);
                    }
                }
            }
            catch
            {
                return serializer.Serialize("Failed.");
            }
            return serializer.Serialize(listInfo);
        }
        private void GetDataButton_OnClick(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            fd.Filter = "JPEG files|*.jpg";
            if (fd.ShowDialog() == true) {
                try {
                    Stream s = fd.OpenFile();
                    byte[] bytes = new byte[s.Length];
                    s.Read(bytes, 0, (int)s.Length);
                    s.Close();

                    // Create hash for image
                    var md5Hash = System.Security.Cryptography.MD5.Create().ComputeHash(bytes);
                    string hashString = md5Hash.Aggregate(String.Empty, (current, hashByte) => current + hashByte.ToString("X2"));

                    var details = new ImageDetails() {
                        Name = System.IO.Path.GetFileName(fd.FileName),
                        Hash = hashString,
                        Tags = imageTagTextBox.Text.Split(new[] {','}),
                        UserId = "Aleksandar Toplek",
                        Created = DateTime.Now,
                        Latitude = 0,
                        Longitude = 0,

                        Size = bytes.Length,
                        Extension = System.IO.Path.GetExtension(fd.FileName)
                    };

                    int partsNeeded = (int)Math.Ceiling((float)bytes.Length/packetSize); // Packets are 20kB
                    bool isUploadNeeded = client.BeginImageUpload(details);
                    if (isUploadNeeded)
                        SendNextPacket(bytes, 0, partsNeeded);
                }
                catch (Exception ex) {
                    System.Diagnostics.Debug.WriteLine(ex);
                }
            }
        }
        public bool BeginImageUploadREST(string name, string tag, string hash, string userId, DateTime created, double longitude, double latitude)
        {
            var details = new ImageDetails() {
                Name = name,
                Tags = new[] {tag},
                Created = created,
                Hash = hash,
                UserId = userId,
                Longitude = longitude,
                Latitude = latitude
            };

            return BeginImageUpload(details);
        }
        public void Add(ImageDetails item)
        {
            db.Open();

            command.Connection = db;
            SqlCeResultSet result;
            command.CommandType = CommandType.TableDirect;
            command.CommandText = table;
            result = command.ExecuteResultSet(ResultSetOptions.Scrollable | ResultSetOptions.Updatable);
            result.Read();

            SqlCeUpdatableRecord record = result.CreateRecord();
            //record.SetInt32(0, item.ImageID);
            record.SetString(1, item.title);
            record.SetDateTime(2, item.date);
            record.SetSqlBinary(3, new SqlBinary(item.image));
            record.SetInt32(4, item.width);
            record.SetInt32(5, item.height);
            result.Insert(record, DbInsertOptions.PositionOnInsertedRow);

            db.Close();
        }
        private void UpdateImageTags(ImageDetails details)
        {
            ImageWallService.CheckIfCacheNeeded();

            // Retireve all image details that match in hash code
            var imageFromDatabase = (from img in ImageWallService.Database.ImageDetailsSet
                                    where img.Hash == details.Hash
                                    select img).ToList();

            // Check if there is image to be updated
            if (imageFromDatabase.Count <= 0) return;

            // Take only first matched image details
            var image = imageFromDatabase.First();

            // Retrieve tags and add new tags to image
            var allTags = this.RetrieveTags(details.Tags);
            foreach (var tag in allTags) {
                if (!image.ImageTag.Contains(tag)) {
                    // Set user and increase size variables
                    tag.User = image.User;

                    // Add tag to image
                    image.ImageTag.Add(tag);
                }

                // Increase tag size and update date
                tag.Date = DateTime.Now;
            }

            // Update image change date if any tag change has happened
            if (allTags.Count > 0)
                image.Date = DateTime.Now;

            // Save changes of image
            ImageWallService.Database.Database.Connection.Open();
            ImageWallService.Database.SaveChanges();
            ImageWallService.Database.Database.Connection.Close();
        }
        private Exception FinishUpload()
        {
            // Combines image parts
            List<byte> imageBytes = new List<byte>();
            this.imageParts.Keys.ToList().Sort();
            foreach (var bytes in this.imageParts.Values) {
                imageBytes.AddRange(bytes);
            }

            // Get absolute tag directory path
            string path = ImageWallService.GetServerImagesPath(imageDetails.Tags.First());

            // Create tag directory if doesn't exist
            if (!Directory.Exists(path)) {
                try {
                    Directory.CreateDirectory(path);
                }
                catch (Exception ex) {
                    System.Diagnostics.Debug.WriteLine(ex);
                    return ex;
                }
            }

            // Add image signature to absoute path
            string imagePath = Path.Combine(path, imageDetails.Hash + imageDetails.Extension);
            string imageThumbnailPath = Path.Combine(path, imageDetails.Hash + "_Thumb.jpg");

            // Save image and it's thumbnail to disk
            this.SaveImageToDisk(imageBytes.ToArray(), imagePath);
            this.CreateImageThumbnail(imageBytes.ToArray(), imageThumbnailPath);

            // Check if databse cache is needed before changing or checking anything
            ImageWallService.CheckIfCacheNeeded();

            // Retrieve tags from image details or create new tags
            var user = RetrieveUser(this.imageDetails.UserId);
            var tags = RetrieveTags(this.imageDetails.Tags);

            // Set tags user
            foreach (var tag in tags) {
                tag.User = user;
                tag.Date = DateTime.Now;
            }

            // Create image details data model
            var imageDetailsModel = new Data.ImageDetails() {
                Name = this.imageDetails.Name,
                Date = this.imageDetails.Created,
                Hash = this.imageDetails.Hash,
                ImageTag = tags,
                Latitude = this.imageDetails.Latitude,
                Longitude = this.imageDetails.Longitude,
                URL = ImageWallService.ToRelativePath(imagePath),
                URLThumb = ImageWallService.ToRelativePath(imageThumbnailPath),
                User = user
            };

            // Add image details and save changes
            ImageWallService.Database.Database.Connection.Open();
            ImageWallService.Database.ImageDetailsSet.Add(imageDetailsModel);
            ImageWallService.Database.SaveChanges();
            ImageWallService.Database.Database.Connection.Close();

            System.Diagnostics.Debug.WriteLine(format: "Image[{0}] Successfully received", args: this.imageDetails.Hash);

            // Set receiving flags to end upload
            this.isReceivingImage = false;
            this.imageDetails = default(ImageDetails);
            this.bytesLeft = 0;
            this.imageParts.Clear();

            // Cache changes
            ImageWallService.CacheDatabase();

            return null;
        }
        public bool BeginImageUpload(ImageDetails details)
        {
            if (details == null || String.IsNullOrEmpty(details.Hash) || details.Size <= 0)
                throw new ImageUploadException("Invalid image details!");

            // Set tag to "Other" if tag is not defined
            if (details.Tags == null || details.Tags.Length <= 0)
                details.Tags = new[] {"Other"};

            // If image exists, only update tags and cancel upload
            if (this.ImageExists(details.Hash)) {
                System.Diagnostics.Debug.WriteLine(format: "Image[{0}] already exists! Updating tags.", args: details.Hash);

                this.UpdateImageTags(details);
                return false;
            }

            // Set receiving flags to begin upload
            this.isReceivingImage = true;
            this.imageDetails = details;
            this.imageParts = new Dictionary<int, byte[]>();
            this.bytesLeft = details.Size;

            return true;
        }