private string getPropertyValue(string imagePath, System.Drawing.Image image, int id) { try { if (image.PropertyIdList.Contains(id)) { return(getPropertyValue(image.GetPropertyItem(id))); } else { TagLib.Image.File tagImage = TagLib.File.Create(imagePath) as TagLib.Image.File; string result = null; if (id == manufacturerId && tagImage.ImageTag.Make != null && tagImage.ImageTag.Make.Length > 0) { result = tagImage.ImageTag.Make; } else if (id == modelId && tagImage.ImageTag.Model != null && tagImage.ImageTag.Model.Length > 0) { result = tagImage.ImageTag.Model; } else if (id == dateTakenId && tagImage.ImageTag.DateTime.HasValue) { result = tagImage.ImageTag.DateTime.Value.ToString(CultureStrings.FormatDateTaken); } else if (id == dateTakenId && !tagImage.ImageTag.DateTime.HasValue) { result = getPropertyValue(image.GetPropertyItem(dateTimeId)); } else if (id == latitudeLongitudeId && tagImage.ImageTag.Latitude.HasValue && tagImage.ImageTag.Longitude.HasValue) { result = tagImage.ImageTag.Latitude + "," + tagImage.ImageTag.Longitude; } tagImage.Dispose(); if (result != null) { return(result); } else { FileWriterWithAppendMode.GlobalWrite(string.Format(CultureStrings.InfomationImageProperties, doubleQuoteText(imagePath), id, convertIntsToText(image.PropertyIdList))); } } } catch (System.Exception ex) { logException(ex); } return(null); }
public static float?GetLatitude(System.Drawing.Image targetImg) { try { //Property Item 0x0001 - PropertyTagGpsLatitudeRef PropertyItem propItemRef = targetImg.GetPropertyItem(1); //Property Item 0x0002 - PropertyTagGpsLatitude PropertyItem propItemLat = targetImg.GetPropertyItem(2); return(ExifGpsToFloat(propItemRef, propItemLat)); } catch (ArgumentException) { return(null); } }
public static float?GetLongitude(System.Drawing.Image targetImg) { try { ///Property Item 0x0003 - PropertyTagGpsLongitudeRef PropertyItem propItemRef = targetImg.GetPropertyItem(3); //Property Item 0x0004 - PropertyTagGpsLongitude PropertyItem propItemLong = targetImg.GetPropertyItem(4); return(ExifGpsToFloat(propItemRef, propItemLong)); } catch (ArgumentException) { return(null); } }
/// <summary> /// Récupère la rotation nécessaire dans les métadonnées de l'image /// </summary> /// <param name="img"></param> /// <returns></returns> private double GetRotation(System.Drawing.Image img) { double rot = 0; if (!img.PropertyIdList.Contains(exifOrientationID)) { return(rot); } var prop = img.GetPropertyItem(exifOrientationID); int val = BitConverter.ToUInt16(prop.Value, 0); if (val == 3 || val == 4) { rot = 180; } else if (val == 5 || val == 6) { rot = 90; } else if (val == 7 || val == 8) { rot = 270; } return(rot); }
/// <summary> /// Returns the creation date of the Photo. The creation date is pulled from either the EXIF data, file name or created date /// </summary> /// <param name="path">Path to the file</param> /// <returns>The file's created date as a DateTime</returns> public DateTime GetDateTaken(string path) { try { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) using (System.Drawing.Image myImage = System.Drawing.Image.FromStream(fs, false, false)) { PropertyItem propItem = myImage.GetPropertyItem(36867); string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2); return(DateTime.Parse(dateTaken)); } } catch (ArgumentException ae) { Utilities.Log("EXIF data not found: " + ae.Message); //the property that returns the date is not found so check the file name for a date string in the name var fileInfo = new FileInfo(path); Regex date_regex = new Regex(@"(19|20)\d\d(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])"); if (date_regex.IsMatch(fileInfo.Name)) { var date_match = date_regex.Match(fileInfo.Name); int year = Int32.Parse(date_match.Value.Substring(0, 4)); int month = Int32.Parse(date_match.Value.Substring(4, 2)); int day = Int32.Parse(date_match.Value.Substring(6, 2)); //Utilities.Log(String.Format("File Name: {3} Date: {0}\\{1}\\{2}", day, month, year, fileInfo.Name)); return(new DateTime(year, month, day)); } //returns the earlier creation date or modifed date else { return(DateTime.Compare(fileInfo.CreationTime.Date, fileInfo.LastWriteTime.Date) > 0 ? fileInfo.LastWriteTime.Date : fileInfo.CreationTime.Date); } } }
private static string ReadImageProperty(System.Drawing.Image image, int ID) { try { var pi = image.GetPropertyItem(ID); if (pi.Type == 2) //ASCII { return(ASCIIencoding.GetString(pi.Value, 0, pi.Len - 1)); } if (pi.Type == 5) //rational { byte[] bb = pi.Value; uint uNominator = BitConverter.ToUInt32(bb, 0); uint uDenominator = BitConverter.ToUInt32(bb, 4); if (uDenominator == 1) { return(uNominator.ToString()); } return(uNominator.ToString() + "/" + uDenominator.ToString()); } } catch { } return("Not Found"); }
public static System.Drawing.Image OrientImage(System.Drawing.Image image) { int orientationId = 0x0112; if (image.PropertyIdList.Contains(orientationId)) { int rotationValue = image.GetPropertyItem(0x0112).Value[0]; switch (rotationValue) { case 1: // landscape, do nothing break; case 8: // rotated 90 right // de-rotate: image.RotateFlip(rotateFlipType: System.Drawing.RotateFlipType.Rotate270FlipNone); break; case 3: // bottoms up image.RotateFlip(rotateFlipType: System.Drawing.RotateFlipType.Rotate180FlipNone); break; case 6: // rotated 90 left image.RotateFlip(rotateFlipType: System.Drawing.RotateFlipType.Rotate90FlipNone); break; } image.RemovePropertyItem(orientationId); } return(image); }
public ImageInfo(System.Drawing.Image image) { this.image = image; this.animated = ImageAnimator.CanAnimate(image); if (this.animated) { this.frameCount = image.GetFrameCount(FrameDimension.Time); PropertyItem propertyItem = image.GetPropertyItem(0x5100); if (propertyItem != null) { byte[] buffer = propertyItem.Value; this.frameDelay = new int[this.FrameCount]; for (int i = 0; i < this.FrameCount; i++) { this.frameDelay[i] = ((buffer[i * 4] + (0x100 * buffer[(i * 4) + 1])) + (0x10000 * buffer[(i * 4) + 2])) + (0x1000000 * buffer[(i * 4) + 3]); } } } else { this.frameCount = 1; } if (this.frameDelay == null) { this.frameDelay = new int[this.FrameCount]; } }
public GifFrame(GifInfoCache info, ImageStorage image, int frameIndex) { BitmapImage imageSource = new BitmapImage(); Stream bitmapStream = new MemoryStream(); image.Save(bitmapStream, ImageFormat.Png); bitmapStream.Seek(0, SeekOrigin.Begin); imageSource.BeginInit(); imageSource.StreamSource = bitmapStream; imageSource.EndInit(); if (imageSource.CanFreeze) { imageSource.Freeze(); } this.ImageSource = imageSource; this.DelayToNextMS = BitConverter.ToInt32(image.GetPropertyItem(kFrameDelayProperty).Value, frameIndex) * 10; if (this.DelayToNextMS == 0 && info.Frames.Count > 0) { this.DelayToNextMS = info.Frames[0].DelayToNextMS; } else { this.DelayToNextMS = 100; } this.FrameIndex = frameIndex; }
private void SetPropertyItemString(System.Drawing.Image image, PropertyTagId id, String value) { byte[] buffer = Encoding.Unicode.GetBytes(value); PropertyItem propItem = image.GetPropertyItem((int)id); propItem.Len = buffer.Length; propItem.Value = buffer; image.SetPropertyItem(propItem); }
//retrieves the datetime WITHOUT loading the whole image public static DateTime GetDateTakenFromImage(string path) { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) using (System.Drawing.Image myImage = System.Drawing.Image.FromStream(fs, false, false)) { System.Drawing.Imaging.PropertyItem propItem = myImage.GetPropertyItem(36867); string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2); return(DateTime.Parse(dateTaken)); } }
public static EXIF GetExif(string filePathname) //public static DateTime? DateTaken(string filePathname) { //return DateTaken(System.Drawing.Image.FromFile(filePathname)); EXIF exif = new EXIF(); System.Drawing.Image img = null; try { img = System.Drawing.Image.FromFile(filePathname); exif.ExifDTOriginal = DateTaken(img, filePathname); if (exif.ExifDTOriginal == null) { Log.Debug(filePathname + " has NO EXIF data"); } else { int Model = 0x0110; //Equipment model //0x010F;//Equipment manufacturer : Company if (img.PropertyIdList.Contains(Model)) { string modelTag = System.Text.Encoding.ASCII.GetString(img.GetPropertyItem(Model).Value); modelTag = modelTag.TrimEnd('\0'); modelTag = modelTag.TrimEnd(); exif.EquipmentModel = modelTag; //Console.Write("Model: " + modelTag); //if (modelTag.IndexOf("9GF00") >= 0) //{ // Console.WriteLine(".<= " + filePathname); //} //else Console.WriteLine("."); } } } catch (OutOfMemoryException e) { Log.Error("[OutOfMemoryException] " + filePathname + " : " + e.Message); //exif.ExifDTOriginal = null; exif = null; } finally { if (img != null) { img.Dispose(); } } return(exif); }
public static DateTime GetDateTimeOriginal(System.Drawing.Image image) { PropertyItem pi = image.GetPropertyItem(36867); //(int)ExifTags.DateTimeOriginal string oldTime = Encoding.ASCII.GetString(pi.Value); oldTime = oldTime.Replace("\0", ""); //时间文本格式化为DateTime IFormatProvider culture = new CultureInfo("zh-CN", true); DateTime time = DateTime.ParseExact(oldTime, "yyyy:MM:dd HH:mm:ss", culture); return(time); }
public ActionResult Add(Image imageModel) { // System.Drawing.Image img = System.Drawing.Image.FromFile("C:/Users/18651/source/repos/WebApplication1/WebApplication1/Image/IMG_8148183549382.JPG"); System.Drawing.Image originalImage = System.Drawing.Image.FromStream(imageModel.ImageFile.InputStream); if (originalImage.PropertyIdList.Contains(0x0112)) { int rotationValue = originalImage.GetPropertyItem(0x0112).Value[0]; switch (rotationValue) { case 1: // landscape, do nothing break; case 8: // rotated 90 right // de-rotate: originalImage.RotateFlip(rotateFlipType: System.Drawing.RotateFlipType.Rotate270FlipNone); break; case 3: // bottoms up originalImage.RotateFlip(rotateFlipType: System.Drawing.RotateFlipType.Rotate180FlipNone); break; case 6: // rotated 90 left originalImage.RotateFlip(rotateFlipType: System.Drawing.RotateFlipType.Rotate90FlipNone); break; } } string fileName = Path.GetFileNameWithoutExtension(imageModel.ImageFile.FileName); string extension = Path.GetExtension(imageModel.ImageFile.FileName); fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension; imageModel.ImagePath = "~/Image/" + fileName; fileName = Path.Combine(Server.MapPath("~/Image/"), fileName); imageModel.ImageFile.SaveAs(fileName); using (DbModels db = new DbModels()) { db.Images.Add(imageModel); db.SaveChanges(); } originalImage.Save(fileName); ModelState.Clear(); return(View()); }
/// <summary> /// retrieves the datetime from the image at the received path /// </summary> /// <param name="path">the path to the image to have its takendate extracted</param> /// <returns>the datetime objects describing its datetaken property</returns> private static DateTime GetDateTakenFromImage(string path) { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) using (System.Drawing.Image myImage = System.Drawing.Image.FromStream(fs, false, false)) { System.Drawing.Imaging.PropertyItem propItem = null; if (myImage.PropertyIdList.Any(x => x == 36867) || myImage.PropertyIdList.Any(x => x == 306)) { if (myImage.PropertyIdList.Any(x => x == 36867)) { propItem = myImage.GetPropertyItem(36867); } else { propItem = myImage.GetPropertyItem(306); } string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2); return(DateTime.Parse(dateTaken)); } //if no property of date taken on the file (picture) take the date of creation return(new FileInfo(path).CreationTime); } }
public static DateTime?DateTaken(System.Drawing.Image getImage, string fName = "") { DateTime?ret = null; int DateTakenValue = 0x9003; //36867; #ExifDTOriginal if (!getImage.PropertyIdList.Contains(DateTakenValue)) { return(ret); } int year = 1901, month = 1, day = 1, hour = 0, minute = 0, second = 0; try { string dateTakenTag = System.Text.Encoding.ASCII.GetString(getImage.GetPropertyItem(DateTakenValue).Value); string[] parts = dateTakenTag.Split(':', ' '); //if (dateTakenTag.Any(x => x == ':')) if (parts.Length == 2) { year = int.Parse(parts[0].Substring(0, 4)); month = int.Parse(parts[0].Substring(4, 2)); day = int.Parse(parts[0].Substring(6, 2)); hour = int.Parse(parts[1].Substring(0, 2)); minute = int.Parse(parts[1].Substring(2, 2)); second = int.Parse(parts[1].Substring(4, 2)); } else //if (parts.Length == 6) { year = int.Parse(parts[0]); month = int.Parse(parts[1]); day = int.Parse(parts[2]); hour = int.Parse(parts[3]); minute = int.Parse(parts[4]); second = int.Parse(parts[5]); } if (year != 0 && month != 0 && day != 0) { ret = new DateTime(year, month, day, hour, minute, second); } } catch (Exception e) { Log.Error("[DateTaken Failed] " + e.Message + "\n(" + fName + ")"); } return(ret); }
private static void ProcessingThread(byte[] gifData, AnimationInfo animationInfo) { System.Drawing.Image gifImage = System.Drawing.Image.FromStream(new MemoryStream(gifData)); FrameDimension dimension = new FrameDimension(gifImage.FrameDimensionsList[0]); int frameCount = gifImage.GetFrameCount(dimension); animationInfo.frameCount = frameCount; animationInfo.initialized = true; int index = 0; int firstDelayValue = -1; for (int i = 0; i < frameCount; i++) { gifImage.SelectActiveFrame(dimension, i); System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(gifImage.Width, gifImage.Height); System.Drawing.Graphics.FromImage(bitmap).DrawImage(gifImage, System.Drawing.Point.Empty); LockBitmap frame = new LockBitmap(bitmap); frame.LockBits(); FrameInfo currentFrame = new FrameInfo(bitmap.Width, bitmap.Height); if (currentFrame.colors == null) { currentFrame.colors = new Color32[frame.Height * frame.Width]; } for (int x = 0; x < frame.Width; x++) { for (int y = 0; y < frame.Height; y++) { System.Drawing.Color sourceColor = frame.GetPixel(x, y); currentFrame.colors[(frame.Height - y - 1) * frame.Width + x] = new Color32(sourceColor.R, sourceColor.G, sourceColor.B, sourceColor.A); } } int delayPropertyValue = BitConverter.ToInt32(gifImage.GetPropertyItem(20736).Value, index); if (firstDelayValue == -1) { firstDelayValue = delayPropertyValue; } currentFrame.delay = delayPropertyValue * 10; animationInfo.frames.Add(currentFrame); index += 4; Thread.Sleep(0); } }
/// <summary> /// Inspect the EXIF metadata for orientation (0x112) /// </summary> /// <param name="image"></param> /// <returns></returns> private int GetRotationIndex(System.Drawing.Image image) { int rotationIndex = 0; try { var prop = image.GetPropertyItem(0x112); int val = BitConverter.ToUInt16(prop.Value, 0); if (val > 0) { rotationIndex = val; } } catch (ArgumentException) { } return(rotationIndex); }
public static void FixExifDateTime(string photoPath, TimeSpan timeSpan) { var files = Directory.GetFiles(photoPath); //获取所有照片路径 IFormatProvider culture = new CultureInfo("zh-CN", true); foreach (var file in files) { //替代System.Drawing.Image.FromFile(file); System.Drawing.Image image = GetImage(file); //获取Exif的DateTimeOriginal属性(36867) PropertyItem pi = image.GetPropertyItem(36867); //(int)ExifTags.DateTimeOriginal //转为时间文本 string oldTime = Encoding.ASCII.GetString(pi.Value); oldTime = oldTime.Replace("\0", ""); Debug.WriteLine(file + " " + oldTime); //时间文本格式化为DateTime DateTime time = DateTime.ParseExact(oldTime, "yyyy:MM:dd HH:mm:ss", culture); //由于是接着ExifToolGui没有改完的目录,所以只转换EXIF记录为timeFalse年份的, //跨年的话要另外处理,因为我这里不跨年,所以简单点 //得到正确的时间 DateTime newTime = time + timeSpan; //转换为EXIF存储的时间格式 string newTimeString = newTime.ToString("yyyy:MM:dd HH:mm:ss"); pi.Value = Encoding.ASCII.GetBytes(newTimeString + "\0"); //修改DateTimeOriginal属性和其他的时间属性 image.SetPropertyItem(pi); pi.Id = 306; // (int)ExifTags.DateTime; //306 image.SetPropertyItem(pi); pi.Id = 36868; //(int)ExifTags.DateTimeDigitized; //36868 image.SetPropertyItem(pi); //存回文件 image.Save(file); image.Dispose(); } }
public GifInfoCache(ImageStorage image) { var frameDimension = new FrameDimension(image.FrameDimensionsList[0]); image.SelectActiveFrame(frameDimension, 0); this.IsLooping = BitConverter.ToInt16(image.GetPropertyItem(kIsLooping).Value, 0) != 1; this.SourcePixelWidth = image.Width; this.SourcePixelHeight = image.Height; int frameCount = image.GetFrameCount(frameDimension); this.Frames = new List <GifFrame>(frameCount); for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) { image.SelectActiveFrame(frameDimension, frameIndex); this.Frames.Add(new GifFrame(this, image, frameIndex)); } }
private void CopyPropertyItem(System.Drawing.Image source, System.Drawing.Image destination, PropertyTagId id) { PropertyItem propItem = source.GetPropertyItem((int)id); destination.SetPropertyItem(propItem); /* * switch (propItem.Type) * { * case 1: //Specifies that Value is an array of bytes. * destination.SetPropertyItem(propItem); * break; * * case 2: //Specifies that Value is a null-terminated ASCII string. If you set the type data member to ASCII type, you should set the Len property to the length of the string including the null terminator. For example, the string "Hello" would have a length of 6. * throw new NotImplementedException(); * break; * * case 3: //Specifies that Value is an array of unsigned short (16-bit) integers. * throw new NotImplementedException(); * break; * * case 4: //Specifies that Value is an array of unsigned long (32-bit) integers. * throw new NotImplementedException(); * break; * * case 5: //Specifies that Value data member is an array of pairs of unsigned long integers. Each pair represents a fraction; the first integer is the numerator and the second integer is the denominator. * throw new NotImplementedException(); * break; * * case 6: //Specifies that Value is an array of bytes that can hold values of any data type. * throw new NotImplementedException(); * break; * * case 7: //Specifies that Value is an array of signed long (32-bit) integers. * throw new NotImplementedException(); * break; * * case 10: //Specifies that Value is an array of pairs of signed long integers. Each pair represents a fraction; the first integer is the numerator and the second integer is the denominator. * throw new NotImplementedException(); * break; * * }*/ }
public System.Drawing.RotateFlipType ExifRotate(System.Drawing.Image img) { // for some reason iText does not respect orientation stored in metadata as it seams... // try to fix it with this weird stuff... // based on https://www.cyotek.com/blog/handling-the-orientation-exif-tag-in-images-using-csharp const int exifOrientationID = 0x112; //274 if (!img.PropertyIdList.Contains(exifOrientationID)) { return(System.Drawing.RotateFlipType.RotateNoneFlipNone); } var prop = img.GetPropertyItem(exifOrientationID); int val = BitConverter.ToUInt16(prop.Value, 0); var rot = System.Drawing.RotateFlipType.RotateNoneFlipNone; if (val == 3 || val == 4) { rot = System.Drawing.RotateFlipType.Rotate180FlipNone; } else if (val == 5 || val == 6) { rot = System.Drawing.RotateFlipType.Rotate90FlipNone; } else if (val == 7 || val == 8) { rot = System.Drawing.RotateFlipType.Rotate270FlipNone; } if (val == 2 || val == 4 || val == 5 || val == 7) { rot |= System.Drawing.RotateFlipType.RotateNoneFlipX; } if (rot != System.Drawing.RotateFlipType.RotateNoneFlipNone) { img.RotateFlip(rot); } return(rot); }
public async Task <IActionResult> UploadUserPhoto(IFormFile file) { if ((file == null) || (!imageWriter.IsImageFile(file))) { return(BadRequest()); } //Create unique UUID file name string fileName = Path.GetFileName(file.FileName); string extension = Path.GetExtension(fileName); string uniqueFileName = Guid.NewGuid().ToString() + extension; //Image url on the server string imageUrl = "\\images\\users\\" + uniqueFileName; //Absolute path to the image on the server string uploads = Path.Combine(_appHostingEnv.WebRootPath, "images", "users"); string path = Path.Combine(uploads, uniqueFileName); //Upload image on the server await imageWriter.UploadImageAsync(file, path); System.Drawing.Image image = System.Drawing.Image.FromFile(path); foreach (var prop in image.PropertyItems) { if (prop.Id == 0x0112) { int orientationValue = image.GetPropertyItem(prop.Id).Value[0]; if (orientationValue != 1) { imageWriter.RotateImage(image, orientationValue); imageWriter.DeleteImage(path); image.Save(path, ImageFormat.Jpeg); break; } break; } } return(Ok(imageUrl)); }
/// <summary> /// get the data from the pic /// </summary> /// <param name="path"></param> /// <returns></returns> private static string getDataFromPic(string path) { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) using (System.Drawing.Image myImage = System.Drawing.Image.FromStream(fs, false, false)) { PropertyItem propItem = null; try { propItem = myImage.GetPropertyItem(36867); } catch { } if (propItem != null) { string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2); return(DateTime.Parse(dateTaken).ToShortDateString()); } else { return(new FileInfo(path).LastWriteTime.ToShortDateString()); } } }
public ImageInfo(System.Drawing.Image image) { this.image = image; this.animated = ImageAnimator.CanAnimate(image); if (this.animated) { this.frameCount = image.GetFrameCount(FrameDimension.Time); PropertyItem propertyItem = image.GetPropertyItem(0x5100); if (propertyItem != null) { byte[] buffer = propertyItem.Value; this.frameDelay = new int[this.FrameCount]; for (int i = 0; i < this.FrameCount; i++) { this.frameDelay[i] = ((buffer[i * 4] + (0x100 * buffer[(i * 4) + 1])) + (0x10000 * buffer[(i * 4) + 2])) + (0x1000000 * buffer[(i * 4) + 3]); } } } else { this.frameCount = 1; } if (this.frameDelay == null) { this.frameDelay = new int[this.FrameCount]; } }
internal void LoadImageDataFromByte(Triggernometry.RealPlugin plug, Graphics g, byte[] data) { GifData gif = GetGifData(data); using (MemoryStream ms = new MemoryStream(data)) { using (System.Drawing.Image i = System.Drawing.Image.FromStream(ms)) { System.Drawing.Bitmap b = (System.Drawing.Bitmap)i; System.Drawing.Imaging.FrameDimension CurrentFd = new System.Drawing.Imaging.FrameDimension(i.FrameDimensionsList[0]); NumberOfFrames = i.GetFrameCount(CurrentFd); IsAnimated = (NumberOfFrames > 1); if (IsAnimated == true) { Frames = new List <Image>(); FrameDelays = new List <int>(); System.Drawing.Imaging.PropertyItem delay = i.GetPropertyItem(0x5100); Color tc; bool hastc = false; if (gif.TransparencyIndex >= 0) { tc = gif.Palette[gif.TransparencyIndex]; hastc = true; } else { tc = gif.Palette[0]; } for (int h = 0; h < NumberOfFrames; h++) { int delayn = (delay.Value[h * 4] + (delay.Value[(h * 4) + 1] * 256)) * 10; FrameDelays.Add(delayn); i.SelectActiveFrame(CurrentFd, h); System.Drawing.Image ifa = ((System.Drawing.Image)i.Clone()); byte[] idata = ImageToByte(ifa); if (hastc == true) { if (gif.TransparencyIndex != gif.BackgroundColor) { // hack in case transparency color is different from bgcolor (some gifs have this shit) SetTransparencyIndex(idata, (byte)gif.BackgroundColor); } else { for (int j = 0; j < gif.TransparencyIndex; j++) { if ((gif.Palette[j].R == tc.R) && (gif.Palette[j].R == tc.G) && (gif.Palette[j].R == tc.B)) { // net itself might have selected an earlier color as new transparency color // hack to reset transparency index to match if so SetTransparencyIndex(idata, (byte)j); break; } } } } Frames.Add(g.CreateImage(idata)); } CurrentFrame = -1; AdvanceFrame(); } else { OriginalImage = g.CreateImage(data); } } } }
/// <param name="filename">Animated Image (ie: animated gif).</param> public static AnimatedImageData GetAnimatedImageData(string fileName) { lock (AnimatedImageDatas) { int index = AnimatedImageDataFileNames.IndexOf(fileName); if (index >= 0) { // AnimatedImageData Already Exists // move it to the end of the array and return it AnimatedImageData data = AnimatedImageDatas[index]; string name = AnimatedImageDataFileNames[index]; AnimatedImageDatas.RemoveAt(index); AnimatedImageDataFileNames.RemoveAt(index); AnimatedImageDatas.Add(data); AnimatedImageDataFileNames.Add(name); return(AnimatedImageDatas[AnimatedImageDatas.Count - 1]); } else { // New AnimatedImageData System.Drawing.Image image = System.Drawing.Image.FromFile(fileName); AnimatedImageData data = new AnimatedImageData(); //// Get Frame Duration int frameDuration = 0; try { System.Drawing.Imaging.PropertyItem frameDelay = image.GetPropertyItem(0x5100); frameDuration = (frameDelay.Value[0] + frameDelay.Value[1] * 256) * 10; } catch { } if (frameDuration > 10) { data.FrameDuration = frameDuration; } else { data.FrameDuration = AnimatedImage.DEFAULT_FRAME_DURATION; } //// Store AnimatedImageData AnimatedImageDatas.Add(data); AnimatedImageDataFileNames.Add(fileName); // Limit amount of Animations in Memory if (AnimatedImageDatas.Count > MAX_ANIMATIONS) { AnimatedImageDatas[0].CancelLoading = true; for (int i = 0; i < AnimatedImageDatas[0].Frames.Count; i++) { AnimatedImageDatas[0]?.Frames[i]?.Dispose(); } AnimatedImageDatas.RemoveAt(0); AnimatedImageDataFileNames.RemoveAt(0); } //// Get Frames LoadingAnimatedImage loadingAnimatedImage = new LoadingAnimatedImage(image, data); Thread loadFramesThread = new Thread(new ThreadStart(loadingAnimatedImage.LoadFrames)); loadFramesThread.Name = "AnimationLoadThread - " + fileName; loadFramesThread.IsBackground = true; loadFramesThread.Start(); while (data.Frames.Count <= 0) { ; // wait for at least one frame to be loaded } return(data); } } }
private void LoadImage(string filename) { FullScreenImage.RenderTransform = null; FullScreenImage.Visibility = Visibility.Visible; FullScreenMedia.Visibility = Visibility.Collapsed; try { using ( var imgStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite)) { using (Image imgForExif = Image.FromStream(imgStream, false, false)) { // Check to see if image display needs to be rotated per EXIF Orientation parameter (274) or user R key input if (Array.IndexOf(imgForExif.PropertyIdList, 274) > -1) { PropertyItem orientation = imgForExif.GetPropertyItem(274); var fType = GetRotateFlipTypeByExifOrientationData((int)orientation.Value[0]); // Check to see if user requested rotation (R key) if (imageRotationAngle == 90) { orientation.Value = BitConverter.GetBytes((int)GetNextRotationOrientation((int)orientation.Value[0])); // Set EXIF tag property to new orientation imgForExif.SetPropertyItem(orientation); // update RotateFlipType accordingly fType = GetRotateFlipTypeByExifOrientationData((int)orientation.Value[0]); //Rotate90(filename); imgForExif.SetPropertyItem(imgForExif.PropertyItems[0]); // Save rotation to file imgForExif.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone); switch (Path.GetExtension(filename).ToLower()) { case ".jpg": imgForExif.Save(filename, ImageFormat.Jpeg); break; case ".png": imgForExif.Save(filename, ImageFormat.Png); break; case ".bmp": imgForExif.Save(filename, ImageFormat.Bmp); break; case ".gif": imgForExif.Save(filename, ImageFormat.Gif); break; } } /* * // Rotate display of image accordingly * fType = GetRotateFlipTypeByExifOrientationData((int)orientation.Value[0]); * if (fType != System.Drawing.RotateFlipType.RotateNoneFlipNone) * { * imgForExif.RotateFlip(fType); * } */ // Get rotation angle accordingly imageRotationAngle = GetBitmapRotationAngleByRotationFlipType(fType); } } var img = new BitmapImage(); img.BeginInit(); img.CacheOption = BitmapCacheOption.OnLoad; //img.UriSource = new Uri(filename); imgStream.Seek(0, SeekOrigin.Begin); // seek stream to beginning img.StreamSource = imgStream; // load image from stream instead of file img.EndInit(); // Rotate Image if necessary TransformedBitmap transformBmp = new TransformedBitmap(); transformBmp.BeginInit(); transformBmp.Source = img; RotateTransform transform = new RotateTransform(imageRotationAngle); transformBmp.Transform = transform; transformBmp.EndInit(); FullScreenImage.Source = transformBmp; // Initialize rotation variable for next image imageRotationAngle = 0; //FullScreenImage.Source = img; imageTimer.Start(); //********* NEW EXIF CODE ************** imgStream.Seek(0, SeekOrigin.Begin); if (Path.GetExtension(filename).ToLower() == ".jpg") // load exif only for jpg { StringBuilder info = new StringBuilder(); info.AppendLine(filename + "\n" + (int)img.Width + "x" + (int)img.Height); var decoder = new JpegBitmapDecoder(imgStream, BitmapCreateOptions.IgnoreColorProfile | BitmapCreateOptions.IgnoreImageCache | BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None); var bitmapFrame = decoder.Frames[0]; if (bitmapFrame != null) { BitmapMetadata metaData = (BitmapMetadata)bitmapFrame.Metadata.Clone(); if (metaData != null) { if (!String.IsNullOrWhiteSpace(metaData.DateTaken)) { info.AppendLine("Date taken: " + metaData.DateTaken); } if (!String.IsNullOrWhiteSpace(metaData.Title)) { info.AppendLine("Title: " + metaData.Title); } if (!String.IsNullOrWhiteSpace(metaData.Subject)) { info.AppendLine("Subject: " + metaData.Subject); } if (!String.IsNullOrWhiteSpace(metaData.Comment)) { info.AppendLine("User comment: " + metaData.Comment); } } } Overlay.Text = info.ToString(); } else { Overlay.Text = filename + "\n" + (int)img.Width + "x" + (int)img.Height; } } } catch { FullScreenImage.Source = null; ShowError("Can not load " + filename + " ! Screensaver paused, press P to unpause."); } }
public GifInfo(string filePath) { bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows); if (System.IO.File.Exists(filePath)) { using (System.Drawing.Image image = System.Drawing.Image.FromFile(filePath)) { this.size = new System.Drawing.Size(image.Width, image.Height); if (image.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif)) { this.frames = new System.Collections.Generic.List <System.Drawing.Image>(); this.fileInfo = new System.IO.FileInfo(filePath); if (System.Drawing.ImageAnimator.CanAnimate(image)) { // Get frames System.Drawing.Imaging.FrameDimension dimension = new System.Drawing.Imaging.FrameDimension(image.FrameDimensionsList[0]); int frameCount = image.GetFrameCount(dimension); int index = 0; int duration = 0; for (int i = 0; i < frameCount; i++) { image.SelectActiveFrame(dimension, i); System.Drawing.Image frame = image.Clone() as System.Drawing.Image; frames.Add(frame); // https://docs.microsoft.com/en-us/dotnet/api/system.drawing.imaging.propertyitem.id?view=dotnet-plat-ext-3.1 // 0x5100 PropertyTagFrameDelay byte[] propertyArray = image.GetPropertyItem(20736).Value; int delay = 0; if (isWindows) { delay = System.BitConverter.ToInt32(propertyArray, index) * 10; } else { delay = System.BitConverter.ToInt32(propertyArray, 0) * 10; } duration += (delay < 100 ? 100 : delay); index += 4; } // Next i this.animationDuration = System.TimeSpan.FromMilliseconds(duration); this.animated = true; this.loop = System.BitConverter.ToInt16(image.GetPropertyItem(20737).Value, 0) != 1; } else { this.frames.Add(image.Clone() as System.Drawing.Image); } } else { throw new System.FormatException("Not valid GIF image format"); } } // End Using image } // End if (System.IO.File.Exists(filePath)) } // End Constructor
public Metadata GetEXIFMetaData(System.Drawing.Image MyImage) { // 创建一个整型数组来存储图像中属性数组的ID int[] MyPropertyIdList = MyImage.PropertyIdList; //创建一个封闭图像属性数组的实例 PropertyItem[] MyPropertyItemList = new PropertyItem[MyPropertyIdList.Length]; //创建一个图像EXIT信息的实例结构对象,并且赋初值 #region 创建一个图像EXIT信息的实例结构对象,并且赋初值 Metadata MyMetadata = new Metadata(); MyMetadata.EquipmentMake.Hex = "10f"; MyMetadata.CameraModel.Hex = "110"; MyMetadata.DatePictureTaken.Hex = "9003"; MyMetadata.ExposureTime.Hex = "829a"; MyMetadata.Fstop.Hex = "829d"; MyMetadata.ShutterSpeed.Hex = "9201"; MyMetadata.MeteringMode.Hex = "9207"; MyMetadata.Flash.Hex = "9209"; MyMetadata.FNumber.Hex = "829d"; //added MyMetadata.ExposureProg.Hex = ""; //added MyMetadata.SpectralSense.Hex = "8824"; //added MyMetadata.ISOSpeed.Hex = "8827"; //added MyMetadata.OECF.Hex = "8828"; //added MyMetadata.Ver.Hex = "9000"; //added MyMetadata.CompConfig.Hex = "9101"; //added MyMetadata.CompBPP.Hex = "9102"; //added MyMetadata.Aperture.Hex = "9202"; //added MyMetadata.Brightness.Hex = "9203"; //added MyMetadata.ExposureBias.Hex = "9204"; //added MyMetadata.MaxAperture.Hex = "9205"; //added MyMetadata.SubjectDist.Hex = "9206"; //added MyMetadata.LightSource.Hex = "9208"; //added MyMetadata.FocalLength.Hex = "920a"; //added MyMetadata.FPXVer.Hex = "a000"; //added MyMetadata.ColorSpace.Hex = "a001"; //added MyMetadata.FocalXRes.Hex = "a20e"; //added MyMetadata.FocalYRes.Hex = "a20f"; //added MyMetadata.FocalResUnit.Hex = "a210"; //added MyMetadata.ExposureIndex.Hex = "a215"; //added MyMetadata.SensingMethod.Hex = "a217"; //added MyMetadata.SceneType.Hex = "a301"; MyMetadata.CfaPattern.Hex = "a302"; #endregion // ASCII编码 System.Text.ASCIIEncoding Value = new System.Text.ASCIIEncoding(); int index = 0; #region 取得数据 int MyPropertyIdListCount = MyPropertyIdList.Length; if (MyPropertyIdListCount != 0) { foreach (int MyPropertyId in MyPropertyIdList) { string hexVal = ""; MyPropertyItemList[index] = MyImage.GetPropertyItem(MyPropertyId); byte[] eixfValueArr = MyImage.GetPropertyItem(MyPropertyId).Value; //Updated by Anders Hu 2004/10/10 string itemValue = BitConverter.ToString(eixfValueArr); //Tag Value值的16进制表示(使用-隔开) string[] longValueArr = itemValue.Split('-'); #region 初始化各属性值 string myPropertyIdString = MyImage.GetPropertyItem(MyPropertyId).Id.ToString("x"); switch (myPropertyIdString) { case "10f": { MyMetadata.EquipmentMake.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); MyMetadata.EquipmentMake.DisplayValue = Value.GetString(MyPropertyItemList[index].Value); break; } case "110": { MyMetadata.CameraModel.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); MyMetadata.CameraModel.DisplayValue = Value.GetString(MyPropertyItemList[index].Value); break; } case "9003": { MyMetadata.DatePictureTaken.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); MyMetadata.DatePictureTaken.DisplayValue = Value.GetString(MyPropertyItemList[index].Value); break; } case "9207": { MyMetadata.MeteringMode.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); MyMetadata.MeteringMode.DisplayValue = LookupEXIFValue("MeteringMode", BitConverter.ToInt16(MyImage.GetPropertyItem(MyPropertyId).Value, 0).ToString()); break; } case "9209": { MyMetadata.Flash.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); MyMetadata.Flash.DisplayValue = LookupEXIFValue("Flash", BitConverter.ToInt16(MyImage.GetPropertyItem(MyPropertyId).Value, 0).ToString()); break; } case "829a": { MyMetadata.ExposureTime.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); string StringValue = ""; for (int Offset = 0; Offset < MyImage.GetPropertyItem(MyPropertyId).Len; Offset = Offset + 4) { StringValue += BitConverter.ToInt32(MyImage.GetPropertyItem(MyPropertyId).Value, Offset).ToString() + "/"; } MyMetadata.ExposureTime.DisplayValue = StringValue.Substring(0, StringValue.Length - 1); break; } case "829d": { MyMetadata.Fstop.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); string[] tempValueArr; tempValueArr = new String[4] { longValueArr[0], longValueArr[1], longValueArr[2], longValueArr[3] }; double exifValueLow = EXIFMetaData.GetLongValue(tempValueArr); tempValueArr = new String[4] { longValueArr[4], longValueArr[5], longValueArr[6], longValueArr[7] }; double exifValueHigth = EXIFMetaData.GetLongValue(tempValueArr); double exifValueRational = EXIFMetaData.GetRationalValue(exifValueLow, exifValueHigth); MyMetadata.FNumber.DisplayValue = "F " + exifValueRational.ToString(); break; } case "9201": { MyMetadata.ShutterSpeed.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); string StringValue = BitConverter.ToInt32(MyImage.GetPropertyItem(MyPropertyId).Value, 0).ToString(); MyMetadata.ShutterSpeed.DisplayValue = "1/" + StringValue + "s"; break; } case "8822": { MyMetadata.ExposureProg.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); MyMetadata.ExposureProg.DisplayValue = LookupEXIFValue("ExposureProg", BitConverter.ToInt16(MyImage.GetPropertyItem(MyPropertyId).Value, 0).ToString()); break; } case "8824": { MyMetadata.SpectralSense.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); MyMetadata.SpectralSense.DisplayValue = Value.GetString(MyPropertyItemList[index].Value); break; } case "8827": { hexVal = ""; MyMetadata.ISOSpeed.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); int length = longValueArr.Length; double longValue = 0.0; for (int i = 0; i < length; ++i) { longValue += Double.Parse(Convert.ToInt64(longValueArr[i], 16).ToString("d")) * Math.Pow(16, i * 2); } MyMetadata.ISOSpeed.DisplayValue = longValue.ToString(); break; } case "8828": { MyMetadata.OECF.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); MyMetadata.OECF.DisplayValue = Value.GetString(MyPropertyItemList[index].Value); break; } case "9000": { MyMetadata.Ver.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); MyMetadata.Ver.DisplayValue = Value.GetString(MyPropertyItemList[index].Value).Substring(1, 1) + "." + Value.GetString(MyPropertyItemList[index].Value).Substring(2, 2); break; } case "9101": { MyMetadata.CompConfig.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); MyMetadata.CompConfig.DisplayValue = LookupEXIFValue("CompConfig", BitConverter.ToInt16(MyImage.GetPropertyItem(MyPropertyId).Value, 0).ToString()); break; } case "9102": { MyMetadata.CompBPP.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); MyMetadata.CompBPP.DisplayValue = BitConverter.ToInt16(MyImage.GetPropertyItem(MyPropertyId).Value, 0).ToString(); break; } case "9202": { hexVal = ""; MyMetadata.Aperture.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); hexVal = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value).Substring(0, 2); hexVal = Convert.ToInt32(hexVal, 16).ToString(); hexVal = hexVal + "00"; MyMetadata.Aperture.DisplayValue = hexVal.Substring(0, 1) + "." + hexVal.Substring(1, 2); break; } case "9203": { hexVal = ""; MyMetadata.Brightness.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); hexVal = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value).Substring(0, 2); hexVal = Convert.ToInt32(hexVal, 16).ToString(); hexVal = hexVal + "00"; MyMetadata.Brightness.DisplayValue = hexVal.Substring(0, 1) + "." + hexVal.Substring(1, 2); break; } case "9204": { MyMetadata.ExposureBias.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); MyMetadata.ExposureBias.DisplayValue = BitConverter.ToInt16(MyImage.GetPropertyItem(MyPropertyId).Value, 0).ToString(); break; } case "9205": { hexVal = ""; MyMetadata.MaxAperture.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); hexVal = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value).Substring(0, 2); hexVal = Convert.ToInt32(hexVal, 16).ToString(); hexVal = hexVal + "00"; MyMetadata.MaxAperture.DisplayValue = hexVal.Substring(0, 1) + "." + hexVal.Substring(1, 2); break; } case "9206": { MyMetadata.SubjectDist.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); MyMetadata.SubjectDist.DisplayValue = Value.GetString(MyPropertyItemList[index].Value); break; } case "9208": { MyMetadata.LightSource.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); MyMetadata.LightSource.DisplayValue = LookupEXIFValue("LightSource", BitConverter.ToInt16(MyImage.GetPropertyItem(MyPropertyId).Value, 0).ToString()); break; } case "920a": { hexVal = ""; MyMetadata.FocalLength.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); hexVal = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value).Substring(0, 2); hexVal = Convert.ToInt32(hexVal, 16).ToString(); hexVal = hexVal + "00"; MyMetadata.FocalLength.DisplayValue = hexVal.Substring(0, 1) + "." + hexVal.Substring(1, 2); break; } case "a000": { MyMetadata.FPXVer.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); MyMetadata.FPXVer.DisplayValue = Value.GetString(MyPropertyItemList[index].Value).Substring(1, 1) + "." + Value.GetString(MyPropertyItemList[index].Value).Substring(2, 2); break; } case "a001": { MyMetadata.ColorSpace.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); if (BitConverter.ToInt16(MyImage.GetPropertyItem(MyPropertyId).Value, 0).ToString() == "1") { MyMetadata.ColorSpace.DisplayValue = "RGB"; } if (BitConverter.ToInt16(MyImage.GetPropertyItem(MyPropertyId).Value, 0).ToString() == "65535") { MyMetadata.ColorSpace.DisplayValue = "Uncalibrated"; } break; } case "a20e": { MyMetadata.FocalXRes.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); MyMetadata.FocalXRes.DisplayValue = BitConverter.ToInt16(MyImage.GetPropertyItem(MyPropertyId).Value, 0).ToString(); break; } case "a20f": { MyMetadata.FocalYRes.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); MyMetadata.FocalYRes.DisplayValue = BitConverter.ToInt16(MyImage.GetPropertyItem(MyPropertyId).Value, 0).ToString(); break; } case "a210": { string aa; MyMetadata.FocalResUnit.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); aa = BitConverter.ToInt16(MyImage.GetPropertyItem(MyPropertyId).Value, 0).ToString();; if (aa == "1") { MyMetadata.FocalResUnit.DisplayValue = "没有单位"; } if (aa == "2") { MyMetadata.FocalResUnit.DisplayValue = "英尺"; } if (aa == "3") { MyMetadata.FocalResUnit.DisplayValue = "厘米"; } break; } case "a215": { MyMetadata.ExposureIndex.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); MyMetadata.ExposureIndex.DisplayValue = Value.GetString(MyPropertyItemList[index].Value); break; } case "a217": { string aa; aa = BitConverter.ToInt16(MyImage.GetPropertyItem(MyPropertyId).Value, 0).ToString(); MyMetadata.SensingMethod.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); if (aa == "2") { MyMetadata.SensingMethod.DisplayValue = "1 chip color area sensor"; } break; } case "a301": { MyMetadata.SceneType.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); MyMetadata.SceneType.DisplayValue = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); break; } case "a302": { MyMetadata.CfaPattern.RawValueAsString = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); MyMetadata.CfaPattern.DisplayValue = BitConverter.ToString(MyImage.GetPropertyItem(MyPropertyId).Value); break; } } #endregion index++; } } #endregion MyMetadata.XResolution.DisplayValue = MyImage.HorizontalResolution.ToString(); MyMetadata.YResolution.DisplayValue = MyImage.VerticalResolution.ToString(); MyMetadata.ImageHeight.DisplayValue = MyImage.Height.ToString(); MyMetadata.ImageWidth.DisplayValue = MyImage.Width.ToString(); MyImage.Dispose(); return(MyMetadata); }
private static void ParseFile(string file) { var ext = Path.GetExtension(file).ToLowerInvariant(); var fileName = Path.GetFileName(file); var validExtensions = new List <string>() { ".jpg", ".png" }; if (!validExtensions.Contains(ext)) { return; } Console.WriteLine($"Processing Image: {Path.GetFileName(file)}"); try { DateTime dateTaken; using (System.Drawing.Image image = System.Drawing.Image.FromFile(file)) { PropertyItem propertyItem = image.GetPropertyItem(0x9003); // DateTime taken ASCIIEncoding encoding = new ASCIIEncoding(); string dateString = encoding.GetString(propertyItem.Value, 0, propertyItem.Len - 1); DateTime.TryParseExact(dateString, "yyyy:MM:dd HH:mm:ss", CultureInfo.CurrentCulture, DateTimeStyles.None, out dateTaken); Console.WriteLine($"Date: {dateTaken}"); image.Dispose(); } if (dateTaken == DateTime.MinValue) { string path = Path.Join(_newDirectory, "No_Date"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (!File.Exists(Path.Join(path, fileName))) { File.Move(file, Path.Join(path, fileName)); } else { ProcessDuplicate(file); } } else { string path2 = Path.Join(_newDirectory, dateTaken.Year.ToString(), dateTaken.Month.ToString()); if (!Directory.Exists(path2)) { Directory.CreateDirectory(path2); } if (!File.Exists(Path.Join(path2, fileName))) { File.Move(file, Path.Join(path2, fileName)); } else { ProcessDuplicate(file); } } } catch (Exception ex) { Console.WriteLine("Error Processing Image", ex); string path = Path.Join(_newDirectory, "Errors"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string newPath = Path.Join(path, fileName); if (!File.Exists(newPath)) { File.Move(file, newPath); } else { ProcessDuplicate(file); } } }