private double GetRotation(EXIFextractor exif) { int orientation = 1; try { var porientation = exif.Cast<Pair>().FirstOrDefault(p => (string)p.First == "Orientation"); orientation = int.Parse((string)porientation.Second); } catch (Exception ex) { var debugException = ex; // Intended } if (orientation == 1) return 0.0; if (orientation == 6) return 90.0; // Other cases not handled for now; see http://sylvana.net/jpegcrop/exif_orientation.html // Here is the algorithm: /* * 1) transform="";; * 2) transform="-flip horizontal";; * 3) transform="-rotate 180";; * 4) transform="-flip vertical";; * 5) transform="-transpose";; * 6) transform="-rotate 90";; * 7) transform="-transverse";; * 8) transform="-rotate 270";; * *) transform="";; */ return 0.0; }
/// <summary> /// Gets the file bytes. /// </summary> /// <param name="context">The context.</param> /// <param name="uploadedFile">The uploaded file.</param> /// <returns></returns> public override Stream GetFileContentStream( HttpContext context, HttpPostedFile uploadedFile ) { if ( uploadedFile.ContentType == "image/svg+xml" ) { return base.GetFileContentStream( context, uploadedFile ); } else { Bitmap bmp = new Bitmap( uploadedFile.InputStream ); // Check to see if we should flip the image. var exif = new EXIFextractor( ref bmp, "\n" ); if ( exif["Orientation"] != null ) { RotateFlipType flip = OrientationToFlipType( exif["Orientation"].ToString() ); // don't flip if orientation is correct if ( flip != RotateFlipType.RotateNoneFlipNone ) { bmp.RotateFlip( flip ); exif.setTag( 0x112, "1" ); // reset orientation tag } } if ( context.Request.QueryString["enableResize"] != null ) { Bitmap resizedBmp = RoughResize( bmp, 1024, 768 ); bmp = resizedBmp; } var stream = new MemoryStream(); bmp.Save( stream, ContentTypeToImageFormat( uploadedFile.ContentType ) ); return stream; } }
/// <summary> /// Gets the file bytes. /// </summary> /// <param name="context">The context.</param> /// <param name="uploadedFile">The uploaded file.</param> /// <returns></returns> public static Stream GetFileContentStream( HttpPostedFile uploadedFile, bool enableResize, bool errorIfNotImage = false ) { if ( uploadedFile.ContentType == "image/svg+xml" || uploadedFile.ContentType == "image/tiff" ) { return uploadedFile.InputStream; } else { try { Bitmap bmp = new Bitmap( uploadedFile.InputStream ); // Check to see if we should flip the image. var exif = new EXIFextractor( ref bmp, "\n" ); if ( exif["Orientation"] != null ) { RotateFlipType flip = OrientationToFlipType( exif["Orientation"].ToString() ); // don't flip if orientation is correct if ( flip != RotateFlipType.RotateNoneFlipNone ) { bmp.RotateFlip( flip ); exif.setTag( 0x112, "1" ); // reset orientation tag } } if ( enableResize ) { Bitmap resizedBmp = RoughResize( bmp, 1024, 768 ); bmp = resizedBmp; } var stream = new MemoryStream(); bmp.Save( stream, ContentTypeToImageFormat( uploadedFile.ContentType ) ); return stream; } catch { if ( errorIfNotImage ) { throw new InvalidDataException( "The file is not a valid image type" ); } // if it couldn't be converted to a bitmap or if the exif or resize thing failed, just return the original stream return uploadedFile.InputStream; } } }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); image = new Bitmap("IMGP0157.JPG"); pb.Image = image; pg.SelectedObject = image; Goheer.EXIF.EXIFextractor er = new Goheer.EXIF.EXIFextractor(ref image, "\r\n"); rtb.Text = string.Empty; foreach (Pair pair in er) rtb.AppendText(pair.First + ": " + pair.Second + "\r\n"); }
/// <summary> /// Initializes a new instance of the <see cref="FileRenameInfo"/> class. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="paddingCount">The padding count.</param> public FileRenameInfo(string fileName, int paddingCount) { file = fileName; try { exif = new EXIFextractor(fileName, "\r\n", string.Empty); } catch (Exception ex) { // no exif data? var debugException = ex; } info = new FileInfo(file); ParseFileName(); indexPaddingCount = paddingCount; Selected = true; }
/// <summary> /// Gets the file bytes. /// </summary> /// <param name="uploadedFile">The uploaded file.</param> /// <param name="resizeIfImage">if set to <c>true</c> [resize if image].</param> /// <returns></returns> public static Stream GetFileContentStream( HttpPostedFile uploadedFile, bool resizeIfImage = true ) { if ( uploadedFile.ContentType == "image/svg+xml" || uploadedFile.ContentType == "image/tiff" || !uploadedFile.ContentType.StartsWith( "image/" ) ) { return uploadedFile.InputStream; } try { var bmp = new Bitmap( uploadedFile.InputStream ); // Check to see if we should flip the image. var exif = new EXIFextractor( ref bmp, "\n" ); if ( exif["Orientation"] != null ) { var flip = OrientationToFlipType( exif["Orientation"].ToString() ); // don't flip if orientation is correct if ( flip != RotateFlipType.RotateNoneFlipNone ) { bmp.RotateFlip( flip ); exif.setTag( 0x112, "1" ); // reset orientation tag } } if ( resizeIfImage ) { bmp = RoughResize( bmp, 1024, 768 ); } var stream = new MemoryStream(); bmp.Save( stream, ContentTypeToImageFormat( uploadedFile.ContentType ) ); return stream; } catch { // if it couldn't be converted to a bitmap or if the exif or resize thing failed, just return the original stream return uploadedFile.InputStream; } }
private void btnGo_Click(object sender, EventArgs e) { if(!Directory.Exists(txtSourceFolder.Text)) { MessageBox.Show("Please choose a valid source directory."); return; } if (!Directory.Exists(txtDestinationFolder.Text)) { try { DirectoryInfo dirInfo = Directory.CreateDirectory(txtSourceFolder.Text); if (!dirInfo.Exists) throw new Exception("Could not create the directory!"); } catch { MessageBox.Show("Please choose a valid destination directory."); return; } } string[] filePaths = Directory.GetFiles(txtSourceFolder.Text, "*", SearchOption.AllDirectories); DateTime datePictureTaken = new DateTime(); System.Text.StringBuilder sb = new System.Text.StringBuilder("Starting."); int i = 0; foreach (string sourceFilePath in filePaths) { i++; progressBar1.Value = (int)(((double)i / (double)filePaths.Length) * 10000); richTextBox1.Text = sb.ToString(); Application.DoEvents(); //forces UI update datePictureTaken = DateTime.MaxValue; FileInfo info = new FileInfo(sourceFilePath); if (info.Exists) { if ((info.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden) { sb.Insert(0, string.Format("File {0} skipped, it is a hidden file.\n", sourceFilePath)); // the file is hidden, skip it. continue; } if ((info.Attributes & FileAttributes.System) == FileAttributes.System) { sb.Insert(0, string.Format("File {0} skipped, it is a system file.\n", sourceFilePath)); // the file is system, skip it. continue; } string[] supportedExtensions = { ".jpeg", ".jpg", ".bmp" , ".gif", ".exif", ".png", ".tiff"}; string extension = info.Extension.ToLower(); if (supportedExtensions.Any(extension.ToLowerInvariant().Contains)) { using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(sourceFilePath)) { // create a new instance of Extractor // class. Here "\n" is the newline // that is used to seprate output of two tags. // You can replace it with "," if you want Goheer.EXIF.EXIFextractor er = new Goheer.EXIF.EXIFextractor(bmp, "\n"); // now dump all the tags on console //Console.Write(er); // to set a tag you have to specify the tag id // code 0x13B is for artist name // since this number has ascii string with // it pass the string you want to set //er.setTag(0x13B, "http://www.goheer.com"); // dispose the image here or do whatever you want. // Extract the tag data using the ExifTags enumeration object temp = er["DTOrig"]; if (temp != null) { if (DateTime.TryParseExact(temp.ToString().Replace("\0", string.Empty).Trim(), "yyyy:MM:dd HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out datePictureTaken)) { if (datePictureTaken.Year < 1950 || datePictureTaken.Year >= 9999) { sb.Insert(0, string.Format("ERROR: File {0}, DTOrig data bad: read as \"{1}\".\n", sourceFilePath, temp.ToString())); DialogResult dr = MessageBox.Show(string.Format("File {0}, read DTOrig as {1}. Creation time is {2}, Last modified time is {3}. Press OK to continue processing this file, cancel to skip.", sourceFilePath, temp.ToString(), info.CreationTime, info.LastWriteTime), "Error", MessageBoxButtons.OKCancel); if(dr != DialogResult.OK) { continue; } } sb.Insert(0, string.Format("File {0}, DTOrig exif data successfully parsed.\n", sourceFilePath)); //we had success reading the exif date, maybe the rotation is set too, we can auto-rotate here. //RotateImage(er, sourceFilePath, ref bmp); } } else { sb.Insert(0, string.Format("ERROR: File {0}, DTOrig was null. Creation time is {1}, Modified time is {2}.\n", sourceFilePath, info.CreationTime, info.LastWriteTime)); DialogResult dr = MessageBox.Show(string.Format("File {0}, DTOrig was null. Creation time is {1}, Modified time is {2}. Press OK to continue processing this file, cancel to skip.", sourceFilePath, info.CreationTime, info.LastWriteTime), "Error", MessageBoxButtons.OKCancel); if (dr != DialogResult.OK) { continue; } } } } if (datePictureTaken == null || datePictureTaken == DateTime.MaxValue)//could not read the exif data for some reason, use the earlier of file creation date or modified date instead. { if (info.LastWriteTime < info.CreationTime) { datePictureTaken = info.LastWriteTime; sb.Insert(0, string.Format("WARNING: File {0}, used last modified date, creation date was newer.\n", sourceFilePath)); } else { datePictureTaken = info.CreationTime; sb.Insert(0, string.Format("WARNING: File {0}, used created date, last modified was newer.\n", sourceFilePath)); } } string destinationFolder = Path.Combine(txtDestinationFolder.Text, datePictureTaken.ToString("yyyy-MM-dd")); if (!Directory.Exists(destinationFolder)) { sb.Insert(0, string.Format("Created Directory {0}.\n", destinationFolder)); Directory.CreateDirectory(destinationFolder); } string destinationFilePath = Path.Combine(destinationFolder, info.Name); try { if(destinationFilePath == sourceFilePath) { sb.Insert(0, string.Format("WARNING: Source and destination are the same for {0}.\n", sourceFilePath)); continue; } if (File.Exists(destinationFilePath)) { FileInfo sourceFileInfo = new FileInfo(sourceFilePath); FileInfo destFileInfo = new FileInfo(destinationFilePath); if (cbOverwrite.Checked) { // now you can safely overwrite it sb.Insert(0, copyFile(sourceFilePath, destinationFilePath)); } else { sb.Insert(0, string.Format("WARNING: did not copy file {0} because a file of the same name already exists at the destination {1}.\n", sourceFilePath, destinationFilePath)); } } else { sb.Insert(0, copyFile(sourceFilePath, destinationFilePath)); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); sb.Insert(0, "EXCEPTION: "+ ex.ToString()+ "\n\n"); } } } sb.Insert(0, string.Format("Done. {0} files processed. \n", i.ToString())); richTextBox1.Text = sb.ToString(); }
/// <summary> /// Initializes a new instance of the <see cref="ImageEditor"/> class. /// </summary> /// <param name="image">The image.</param> public ImageEditor(Image image) { Image = image; InterpolationMode = InterpolationMode.Default; _exif = new EXIFextractor(Image); }
/// <summary> /// Collects metadata about the file for real. /// </summary> private void ProcessFR() { if (base.ContiueProcessing()) { try { Bitmap bmp = new Bitmap(File.FullName); MediaFile.Width = bmp.Width; MediaFile.Height = bmp.Height; MediaFile.Resolution = bmp.HorizontalResolution; List<string> keywordlist = Gfx.iMagickMetadata(File.FullName); string keywords = ""; int counter = 0; foreach (string s in keywordlist) { counter++; keywords = keywords + s; if (counter < keywordlist.Count) keywords = keywords + ","; } if (keywords.Length > 0) MediaFile.Keywords = keywords; try { EXIFextractor exif = new EXIFextractor(ref bmp, ""); object o; if ((o = exif["Image Description"]) != null) { MediaFile.Description = o.ToString(); // string kaka = o.ToString(); } if ((o = exif["Copyright"]) != null) MediaFile.Copyright = o.ToString(); string sexif = exif.ToString().Trim(); if (sexif.Length > 0) MediaFile.Exif = sexif; } catch (Exception e) { Log.Notice("Unable to extract EXIF from {0}: {1}\n", File.FullName, e.Message); } GeneratePreviews(bmp); bmp.Dispose(); bmp = null; // Let's remove this in order to let us generate data w/o saving // SaveFile(); } catch (Exception e) { Log.Warning("Unable to handle file ({0}): {1}\n{2}\n", File.FullName, e.Message, e.StackTrace); Log.File("Unable to handle file ({0}): {1}\n{2}\n", File.FullName, e.Message, e.StackTrace); } } }
static void Main(string[] args) { //var inputDirectory = @"D:\Pictures\Test\Source"; var inputDirectory = @"D:\Pictures\_Photos to sort"; //var inputDirectory = @"C:\Users\Tim\Desktop\temp"; var outputDirectory = @"D:\Pictures\Digital Photos"; var inputFiles = Directory.GetFiles(inputDirectory, "*.*", SearchOption.AllDirectories); foreach (var file in inputFiles) { try { var bmp = new Bitmap(file); var exifData = new EXIFextractor(ref bmp, "\n"); var stringDate = exifData["DTOrig"] as string; if (stringDate == null) stringDate = exifData["Date Time"] as string; bmp.Dispose(); var dateTime = DateTime.MinValue; if (stringDate == null) { // Attempt to read date from filename var dateRegex1 = new Regex("(?<year>20[0-9]{2})_(?<month>[0-9]{2})(?<day>[0-9]{2})_(?<hour>[0-9]{2})(?<minute>[0-9]{2})(?<second>[0-9]{2})"); var dateRegex2 = new Regex("(?<year>20[0-9]{2})(?<month>[0-9]{2})(?<day>[0-9]{2})-(?<hour>[0-9]{2})(?<minute>[0-9]{2})(?<second>[0-9]{2})"); if (dateRegex1.IsMatch(file)) { dateTime = DateTime.ParseExact(dateRegex1.Match(file).Value, "yyyy_MMdd_HHmmss", System.Globalization.CultureInfo.CurrentCulture); } else if (dateRegex2.IsMatch(file)) { dateTime = DateTime.ParseExact(dateRegex2.Match(file).Value, "yyyyMMdd-HHmmss", System.Globalization.CultureInfo.CurrentCulture); } else { //var errorDirectory = string.Format(@{0}\Errors", outputDirectory); //if (!Directory.Exists(errorDirectory)) //{ // Console.WriteLine("Creating directory: {0}", errorDirectory); // Directory.CreateDirectory(errorDirectory); //} //Console.WriteLine("No date found in file: {0}", file); //var errorFile = string.Format(@"{0}\{1}", errorDirectory, new FileInfo(file).Name); //if (!File.Exists(errorFile)) // File.Copy(file, errorFile); continue; } } if(dateTime == DateTime.MinValue) dateTime = DateTime.ParseExact(stringDate, "yyyy:MM:dd HH:mm:ss\0", System.Globalization.CultureInfo.CurrentCulture); var datedDirectory = string.Format(@"{0}\{1}\{2}\", outputDirectory, dateTime.ToString("yyyy"), dateTime.ToString("MM")); if (!Directory.Exists(datedDirectory)) { Console.WriteLine("Creating directory: {0}", datedDirectory); Directory.CreateDirectory(datedDirectory); } var attempt = 1; while (true) { //var datedFile = string.Format("{0}_{1}.jpg", dateTime.ToString(@"yyyy-MM-dd_HH-mm-ss"), attempt.ToString("00")); var suffix = string.Empty; if (attempt > 1) suffix = string.Format("-{0}", attempt); var datedFile = string.Format("{0}{1}{2}", dateTime.ToString(@"yyyyMMdd-HHmmss"), suffix, new FileInfo(file).Extension).ToLower(); var outputFile = string.Concat(datedDirectory, datedFile); if (!File.Exists(outputFile)) { Console.WriteLine("Moving file: {0} to {1}", file, outputFile); //File.Copy(file, outputFile); File.Move(file, outputFile); break; } else { var checksum1 = GetChecksum(file); var checksum2 = GetChecksum(outputFile); if (checksum1 == checksum2) { //Console.WriteLine("File already exists: {0} is identical to {1}", file, outputFile); File.Delete(file); break; } attempt++; } } } catch (Exception e) { Console.WriteLine("ERROR PROCESSING FILE: {0}", file); Console.WriteLine(e.Message); } } Console.WriteLine("Deleting empty directories."); DeleteEmptyDirectories(inputDirectory); Console.WriteLine("Done."); Console.ReadLine(); }
public static string ProcessMemberPhoto(Member member, int PhotoCollectionID, Image image, DateTime TakenDT, bool SnappedFromMobile) { string GlobalWebID = UniqueID.NewWebID(); string FileName = GlobalWebID + @".jpg"; Bitmap bmp = (Bitmap)image; try { EXIFextractor exif = new EXIFextractor(ref bmp, string.Empty); if (exif.DTTaken.Year != 1900) { TakenDT = exif.DTTaken; } } catch { } Photo photo = new Photo(); photo.Active = true; photo.Mobile = SnappedFromMobile; photo.MemberID = member.MemberID; photo.WebPhotoID = GlobalWebID; photo.PhotoCollectionID = PhotoCollectionID; photo.TakenDT = TakenDT; photo.CreatedDT = DateTime.Now; // create the large photo // just store the large image.. dont make a resource record System.Drawing.Image MainImage = Photo.ResizeTo800x600(image); string Savepath = member.NickName + @"\" + "plrge" + @"\" + FileName; Photo.SaveToDiskNoCompression(MainImage, Savepath); //create the medium photo.PhotoResourceFile = new ResourceFile(); photo.PhotoResourceFile.WebResourceFileID = GlobalWebID; photo.PhotoResourceFile.ResourceType = (int)ResourceFileType.PhotoLarge; photo.PhotoResourceFile.Path = member.NickName + "/" + "pmed" + "/"; photo.PhotoResourceFile.FileName = FileName; photo.PhotoResourceFile.Save(); System.Drawing.Image MediumImage = Photo.Resize480x480(MainImage); Photo.SaveToDisk(MediumImage, photo.PhotoResourceFile.SavePath); //create the thumbnail photo.ThumbnailResourceFile = new ResourceFile(); photo.ThumbnailResourceFile.WebResourceFileID = GlobalWebID; photo.ThumbnailResourceFile.ResourceType = (int)ResourceFileType.PhotoThumbnail; photo.ThumbnailResourceFile.Path = member.NickName + "/" + "pthmb" + "/"; photo.ThumbnailResourceFile.FileName = FileName; photo.ThumbnailResourceFile.Save(); System.Drawing.Image ThumbnailImage = Photo.ScaledCropTo121x91(MediumImage); Photo.SaveToDisk(ThumbnailImage, photo.ThumbnailResourceFile.SavePath); // attached the resource ids to the photos photo.ThumbnailResourceFileID = photo.ThumbnailResourceFile.ResourceFileID; photo.PhotoResourceFileID = photo.PhotoResourceFile.ResourceFileID; photo.Save(); // update the number of photos MemberProfile memberProfile = member.MemberProfile[0]; memberProfile.NumberOfPhotos++; memberProfile.Save(); return photo.WebPhotoID; }