/// <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> /// /// </summary> /// <param name="picture"></param> private void FillPicture2Detail(PictureModel picture) { var img = new Bitmap(picture.EPath); var ef = new EXIFextractor(ref img, ""); this.pictureBox2.ImageLocation = picture.EPath; this.txtName.Text = picture.EName; this.txtDate.Text = picture.ETakeTime.IsValid() ? picture.ETakeTime.ToString("yyyy-MM-dd HH:mm:ss") : ""; this.txtLocation.Text = picture.ETakeLocation; this.txtTags1.Text = picture.ETags1; this.txtTags2.Text = picture.ETags2; this.txtDescription.Text = picture.EDescription; }
/// <summary> /// Saves the data. /// </summary> /// <param name="context">The context.</param> /// <param name="uploadedFile"></param> /// <param name="file">The file.</param> /// <param name="fileType"></param> public override void SaveData(HttpContext context, HttpPostedFile uploadedFile, BinaryFile file, BinaryFileType fileType) { // Check to see if we should flip the image. try { file.FileName = Path.GetFileName(uploadedFile.FileName); file.MimeType = uploadedFile.ContentType; Bitmap bmp = new Bitmap(uploadedFile.InputStream); var exif = new EXIFextractor(ref bmp, "\n"); if (exif["Orientation"] != null) { RotateFlipType flip = OrientationToFlipType(exif["Orientation"].ToString()); if (flip != RotateFlipType.RotateNoneFlipNone) // don't flip if orientation is correct { bmp.RotateFlip(flip); exif.setTag(0x112, "1"); // reset orientation tag } } if (context.Request.QueryString["enableResize"] != null) { Bitmap resizedBmp = RoughResize(bmp, 1024, 768); bmp = resizedBmp; } using (var stream = new MemoryStream()) { bmp.Save(stream, ContentTypeToImageFormat(file.MimeType)); if (file.Data == null) { file.Data = new BinaryFileData(); } file.Data.Content = stream.ToArray(); } // Use provider to persist file var provider = fileType != null ? ProviderContainer.GetComponent(fileType.StorageEntityType.Name) : ProviderContainer.DefaultComponent; provider.SaveFile(file, null); } catch (Exception ex) { ExceptionLogService.LogException(ex, context); } }
private static void RotateByExif(Bitmap bitmap) { var exif = new EXIFextractor(ref bitmap, "n"); if (exif["Orientation"] != null) { RotateFlipType flip = OrientationToFlipType(exif["Orientation"].ToString()); if (flip != RotateFlipType.RotateNoneFlipNone) // don't flip of orientation is correct { bitmap.RotateFlip(flip); exif.setTag(0x112, "1"); // Optional: reset orientation tag } } }
private void autoRotate(ref EXIFextractor exif, ref Bitmap bmp, FileInfo file) { //Auto-Rotate file if (exif["Orientation"] != null) { string orient = exif["Orientation"].ToString(); RotateFlipType flip = OrientationToFlipType(exif["Orientation"].ToString().TrimEnd('\0')); if (flip != RotateFlipType.RotateNoneFlipNone) // don't flip of orientation is correct { bmp.RotateFlip(flip); // Optional: reset orientation tag try { //exif.setTag(0x112, "1"); doesn't work int propertyId = 0x112; int propertyLen = 2; short propertyType = 3; byte[] propertyValue = { 1, 0 }; exif.setTag(propertyId, propertyLen, propertyType, propertyValue); } catch { } switch (file.Extension.ToLower()) { case ".png": bmp.Save(file.FullName, ImageFormat.Png); break; case ".bmp": bmp.Save(file.FullName, ImageFormat.Bmp); break; case ".gif": bmp.Save(file.FullName, ImageFormat.Gif); break; default: bmp.Save(file.FullName, ImageFormat.Jpeg); break; } } } }
public static void Rotate(string path) { Bitmap bmp = new Bitmap(path); EXIFextractor exif = new EXIFextractor(ref bmp, "n"); if (exif["Orientation"] != null) { RotateFlipType flip = OrientationToFlipType(exif["Orientation"].ToString()); if (flip != RotateFlipType.RotateNoneFlipNone) { bmp.RotateFlip(flip); exif.setTag(0x112, "1"); bmp.Save(path, ImageFormat.Jpeg); bmp.Dispose(); } } }
protected void FlipImageIfNeeded(Image source, Image destination) { base.ExecuteMethod("FlipImageIfNeeded", delegate() { // Rotate the image according to EXIF data EXIFextractor exif = new EXIFextractor(ref source, "n"); if (exif["Orientation"] != null) { RotateFlipType flip = this.ExifOrientationToFlipType(exif["Orientation"].ToString()); if (flip != RotateFlipType.RotateNoneFlipNone) // don't flip of orientation is correct { destination.RotateFlip(flip); } } }); }
public ActionResult imagehihi() { var listImage = _pictureService.GetPictures(); foreach (var item in listImage) { #region [chinh sua hinh anh de khong bi xoay hinh] var path = ""; var bmp = new Bitmap(200, 200); try { path = @"D:\Cong Ty\humiland\humiland\Labixa\Labixa" + item.Url.Replace("/", @"\"); bmp = new Bitmap(path); } catch (Exception) { continue; } var exif = new EXIFextractor(ref bmp, "n"); // get source from http://www.codeproject.com/KB/graphics/exifextractor.aspx?fid=207371 if (exif["Orientation"] != null) { RotateFlipType flip = OrientationToFlipType(exif["Orientation"].ToString().Substring(0, 1).Trim(), path); if (flip != RotateFlipType.RotateNoneFlipNone) // don't flip of orientation is correct { bmp.RotateFlip(flip); exif.setTag(0x112, "1"); // Optional: reset orientation tag if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } bmp.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg); // Dispose of the image files. bmp.Dispose(); } } #endregion } return(View()); }
private string GetCameraModel(EXIFextractor exif) { string cameraModel = ""; if (exif["Equip Model"] != null) { if (exif["Equip Model"] != null) { cameraModel = exif["Equip Model"].ToString().TrimEnd('\0').Trim(); } } else { if (exif["Equip Make"] != null) { cameraModel = exif["Equip Make"].ToString().TrimEnd('\0').Trim(); } } return(cameraModel); }
/* RESTORE * public static media_repo pushXMPdb(media_repo media, string pathToImageFile) { * * Bitmap bmp = new Bitmap(pathToImageFile); * BitmapMetadata Mdata = (BitmapMetadata)bmp.Metadata; * string date = md.DateTaken; * //object t = Mdata.GetQuery(@"/xmp/tiff:model"); * * * * return media; * * }*/ /// <summary> </summary> public static string setOrientation(string pathToImageFile) { //http://dotmac.rationalmind.net/2009/08/correct-photo-orientation-using-exif/ // Rotate the image according to EXIF data Bitmap bmp = new Bitmap(pathToImageFile); EXIFextractor exif = new EXIFextractor(ref bmp, "\n"); // get source from http://www.codeproject.com/KB/graphics/exifextractor.aspx?fid=207371 string values = ""; foreach (System.Web.UI.Pair s in exif) { // Remember the data is returned // in a Key,Value Pair object values += " - " + s.First + " " + s.Second; } log.Info("setOrientation at path " + pathToImageFile + " with" + values); if (exif["Orientation"] != null) { RotateFlipType flip = OrientationToFlipType(int.Parse(exif["Orientation"].ToString())); if (flip != RotateFlipType.RotateNoneFlipNone) // don't flip of orientation is correct { bmp.RotateFlip(flip); exif.setTag(0x112, "1"); // Optional: reset orientation tag bmp.Save(pathToImageFile, ImageFormat.Jpeg); } } String or = null; if (exif["Image Width"] != null && exif["Image Height"] != null) { or = int.Parse(exif["Image Width"].ToString()) > int.Parse(exif["Image Height"].ToString()) ? "h" : "v"; } if (String.IsNullOrEmpty(or)) { System.Drawing.Image img = System.Drawing.Image.FromFile(pathToImageFile); int width = img.Width; int height = img.Height; or = width > height ? "h" : "v"; log.Info("exif was null so W:" + width + " & H:" + height + " --- producing:" + or); } return(or); }
/// <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 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> /// Saves the data. /// </summary> /// <param name="context">The context.</param> /// <param name="inputStream">The input stream.</param> /// <param name="file">The file.</param> public override void SaveData(HttpContext context, Stream inputStream, BinaryFile file) { // Check to see if we should flip the image. try { Bitmap bmp = new Bitmap(inputStream); var exif = new EXIFextractor(ref bmp, "\n"); if (exif["Orientation"] != null) { RotateFlipType flip = OrientationToFlipType(exif["Orientation"].ToString()); if (flip != RotateFlipType.RotateNoneFlipNone) // don't flip if orientation is correct { bmp.RotateFlip(flip); exif.setTag(0x112, "1"); // reset orientation tag } } if (context.Request.QueryString["enableResize"] != null) { Bitmap resizedBmp = RoughResize(bmp, 1024, 768); bmp = resizedBmp; } using (MemoryStream stream = new MemoryStream()) { bmp.Save(stream, ContentTypeToImageFormat(file.MimeType)); if (file.Data == null) { file.Data = new BinaryFileData(); } file.Data.Content = stream.ToArray(); stream.Close(); } } catch { // TODO: Log unable to rotate and/or resize. } }
public static MetaDataItem[] GetExifData(string imageFilename) { List <MetaDataItem> ret = new List <MetaDataItem>(); try { Bitmap mbp = new Bitmap(imageFilename); ret.Add(new MetaDataItem("IMAGE:Width", mbp.Width)); ret.Add(new MetaDataItem("IMAGE:Height", mbp.Height)); try { string sp = ""; EXIFextractor exif = new EXIFextractor(ref mbp, sp); foreach (PairOfObjects s in exif) { if (s.Second.ToString().Trim() != "" && s.Second.ToString() != "0" && s.Second.ToString() != "-") { MetaDataItem i = new MetaDataItem("EXIF:" + s.First, s.Second.ToString().Trim()); ret.Add(i); } } } finally { mbp.Dispose(); } } catch (Exception ex) { Console.Write(ex.Message); } return(ret.ToArray()); }
/// <summary> /// 轉換成Image並旋轉 /// </summary> /// <param name="file"></param> /// <returns></returns> private Image <Bgr, byte> FileToImageRotate(HttpPostedFileBase file) { using (MemoryStream ms = new MemoryStream()) { var theImage = Image.FromStream(file.InputStream); Bitmap bitmap = new Bitmap(theImage); MemoryStream stream = new MemoryStream(); foreach (var item in theImage.PropertyItems) { bitmap.SetPropertyItem(item); } var exif = new EXIFextractor(ref bitmap, "n"); RotateFlipType flip = _webModel.GetOrientationToFlipType(exif["Orientation"] == null ? "0" : exif["Orientation"].ToString()); if (flip != RotateFlipType.Rotate180FlipNone) { foreach (var item in theImage.PropertyItems) { bitmap.SetPropertyItem(item); } } bitmap.RotateFlip(flip); //先不做回存tag動作(有BUG) //exif.setTag(0x112, "1"); // Optional: reset orientation tag bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); stream.Position = 0; byte[] image = new byte[stream.Length + 1]; stream.Read(image, 0, image.Length); var faceImage = new Image <Bgr, byte>(new Bitmap(stream)); return(faceImage); } }
public static byte[] FixEXIF(byte[] originalImage) { Bitmap bmp; using (var ms = new MemoryStream(originalImage)) { bmp = (Bitmap)Image.FromStream(ms, true, true); var exif = new EXIFextractor(ref bmp, "\n"); byte[] orientedImage = originalImage; RotateFlipType flip = RotateFlipType.RotateNoneFlipNone; if (exif["Orientation"] != null) { flip = OrientationToFlipType(exif["Orientation"].ToString()); // 0x112 is the id of the orientation if (flip != RotateFlipType.RotateNoneFlipNone) { bmp.RotateFlip(flip); // reset EXIF orientation int propertyId = 0x112; int propertyLen = 2; short propertyType = 3; byte[] propertyValue = { 1, 0 }; exif.setTag(propertyId, propertyLen, propertyType, propertyValue); } using (MemoryStream saveMs = new MemoryStream()) { bmp.Save(saveMs, System.Drawing.Imaging.ImageFormat.Jpeg); orientedImage = saveMs.ToArray(); } } bmp.Dispose(); return(orientedImage); } }
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); }
public Camera(string url) { EXIFextractor er2 = new EXIFextractor(url, "", ""); }
/// <summary> /// Perform a deep Copy of the object. /// </summary> /// <typeparam name="T">The type of object being copied.</typeparam> /// <param name="source">The object instance to copy.</param> /// <returns>The copied object.</returns> //public static T Clone<T>(this T source) //{ // if (!typeof(T).IsSerializable) // throw new ArgumentException("The type must be serializable.", "source"); // // Don't serialize a null object, simply return the default for that object // if (Object.ReferenceEquals(source, null)) // return default(T); // var Ser = new XmlSerializer(typeof(T)); // using (var Ms = new MemoryStream()) // { // Ser.Serialize(Ms, source); // Ms.Seek(0, SeekOrigin.Begin); // return (T)Ser.Deserialize(Ms); // } //} public static void AsignarDocumentoDetalle(DocumentoDetalleBE DocumentoDetalle, DocumentoBE Documento, String IdValor, CheckBox chkAprobado, HtmlInputHidden hfComentario, DropDownList ddlValor = null, TextBox txtValor = null, HiddenField hfValor = null, String strRutaArchivo = null, Type tipo = null) { DocumentoDetalle = new DocumentoDetalleBE(); DocumentoDetalle.Documento = Documento; DocumentoDetalle.Campo.IdValor = IdValor; DocumentoDetalle.Aprobado = chkAprobado.Checked; DocumentoDetalle.Comentario = hfComentario.Value.ToUpper(); if (ddlValor != null) { DocumentoDetalle.IdValor = ddlValor.SelectedValue; DocumentoDetalle.ValorCadena = ddlValor.SelectedItem.Text; } else if (txtValor != null) { if (tipo != null && tipo.Equals(Type.GetType("System.DateTime"))) { if (!txtValor.Text.Equals("")) { DocumentoDetalle.ValorFecha = Convert.ToDateTime(txtValor.Text); } } else if (tipo != null && tipo.Equals(Type.GetType("System.String"))) { DocumentoDetalle.ValorCadena = txtValor.Text.ToUpper(); } else if (tipo != null && tipo.Equals(Type.GetType("System.Double"))) { if (!txtValor.Text.Equals("")) { DocumentoDetalle.ValorNumerico = Convert.ToDouble(txtValor.Text); } } else if (tipo != null && tipo.Equals(Type.GetType("System.Int32"))) { if (!txtValor.Text.Equals("")) { //DocumentoDetalle.ValorEntero = Convert.ToInt32(txtValor.Text); DocumentoDetalle.ValorEntero = Convert.ToInt32(Convert.ToDouble(txtValor.Text)); } } } else if (hfValor != null) { if (tipo != null && tipo.Equals(Type.GetType("System.Byte[]"))) { if (!hfValor.Value.Equals("")) { DocumentoDetalle.ExtensionArchivo = Path.GetExtension(strRutaArchivo + "\\" + hfValor.Value).ToLower(); #region Agregado Carlos Ramos 19/06/2018 De ser necesario Se cambia la orientacion de la imagen if (DocumentoDetalle.ExtensionArchivo.Equals(".jpg")) { var bmp = new Bitmap(strRutaArchivo + "\\" + hfValor.Value); var exif = new EXIFextractor(ref bmp, "n"); // get source from http://www.codeproject.com/KB/graphics/exifextractor.aspx?fid=207371 if (exif["Orientation"] != null) { RotateFlipType flip = OrientationToFlipType(exif["Orientation"].ToString()); if (flip != RotateFlipType.RotateNoneFlipNone) // don't flip of orientation is correct { bmp.RotateFlip(flip); exif.setTag(0x112, "1"); // Optional: reset orientation tag bmp.Save(strRutaArchivo + "\\" + hfValor.Value); } } } #endregion DocumentoDetalle.ValorBinario = File.ReadAllBytes(strRutaArchivo + "\\" + hfValor.Value); } } } Documento.Detalles.Add(DocumentoDetalle.Clone()); }
public JsonResult UploadImage(FormCollection collection) { bool isSavedSuccessfully = true; var id = collection["Product.Id"]; string fName = ""; try { foreach (string fileName in Request.Files) { HttpPostedFileBase file = Request.Files[fileName]; //Save file content goes here fName = file.FileName; if (file != null && file.ContentLength > 0) { var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Product\\" + User.Identity.Name.ToString() + id, Server.MapPath(@"\"))); string pathString = originalDirectory.ToString();// System.IO.Path.Combine(originalDirectory.ToString(), User.Identity.Name.ToString()); var fileName1 = Path.GetFileName(file.FileName); bool isExists = System.IO.Directory.Exists(pathString); if (!isExists) { System.IO.Directory.CreateDirectory(pathString); } var path = string.Format("{0}\\{1}", pathString, file.FileName); // file.SaveAs(path); #region [chinh sua hinh anh de khong bi xoay hinh] var bmp = new Bitmap(path); var exif = new EXIFextractor(ref bmp, "n"); // get source from http://www.codeproject.com/KB/graphics/exifextractor.aspx?fid=207371 if (exif["Orientation"] != null) { RotateFlipType flip = OrientationToFlipType(exif["Orientation"].ToString().Substring(0, 1).Trim(), path); if (flip != RotateFlipType.RotateNoneFlipNone) // don't flip of orientation is correct { bmp.RotateFlip(flip); exif.setTag(0x112, "1"); // Optional: reset orientation tag if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } bmp.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg); // Dispose of the image files. bmp.Dispose(); } } #endregion } } } catch (Exception ex) { isSavedSuccessfully = false; } if (isSavedSuccessfully) { var product = _productService.GetProductById(int.Parse(id)); var pic = new Picture(); pic.IsDeleted = false; pic.Url = "/Images/Product/" + User.Identity.Name.ToString() + product.Id + "/" + fName; _pictureService.CreatePicture(pic); ProductPictureMapping mapping = new ProductPictureMapping(); mapping.ProductId = product.Id; mapping.PictureId = pic.Id; product.ProductPictureMappings.Add(mapping); _productService.EditProduct(product); return(Json(new { Message = "/Images/Product/" + User.Identity.Name.ToString() + product.Id + "/" + fName, Id = mapping.Id })); } else { return(Json(new { Message = "Error in saving file" })); } }
private void processPicture(FileInfo pictureFile, string authenticationID, string sfAppID, string prefix, string suffix, bool useCameraMake, ref List <string> moveErrors, ref List <string> uploadErrors) { if (pictureFile.Name == "Thumbs.db" || pictureFile.Extension == ".ini") { return; //skip } //Set Defaults DateTime myDateTaken = DateTime.Now; StringBuilder newFileName = new StringBuilder(); newFileName.Append(prefix); newFileName.Append(myDateTaken.ToString("yyyyMMdd_HHmmss")); string ext = pictureFile.Extension.ToLower(); string moveToPath = CreatePicDirStructure(ref myDateTaken); Bitmap bmp; try { bmp = new Bitmap(pictureFile.FullName); } catch { moveErrors.Add(pictureFile.Name); moveToManualFolder(pictureFile.FullName, importDir, newFileName.ToString(), ext); return; } EXIFextractor exif = new EXIFextractor(ref bmp, "n"); // get source from http://www.codeproject.com/KB/graphics/exifextractor.aspx?fid=207371 //Get Date Taken if (exif["Date Time"] != null) { myDateTaken = DateTime.ParseExact(exif["Date Time"].ToString().TrimEnd('\0'), "yyyy:MM:dd HH:mm:ss", null); newFileName.Clear(); newFileName.Append(prefix); newFileName.Append(myDateTaken.ToString("yyyyMMdd_HHmmss")); moveToPath = CreatePicDirStructure(ref myDateTaken); } //Auto Rotate autoRotate(ref exif, ref bmp, pictureFile); bmp.Dispose(); if (useCameraMake) { string cameraModel = GetCameraModel(exif); if (cameraModel != "") { newFileName.Append("_"); newFileName.Append(cameraModel); } } newFileName.Append(suffix); string result = ""; //Attempt to move if (moveToPath != "Error") { try { result = movePicture(pictureFile.FullName, moveToPath, newFileName.ToString(), ext); } catch { moveErrors.Add(pictureFile.Name); moveToManualFolder(pictureFile.FullName, importDir, newFileName.ToString(), ext); } if (result == "Error") { moveErrors.Add(pictureFile.Name); moveToManualFolder(pictureFile.FullName, importDir, newFileName.ToString(), ext); } else { if (!authenticationID.StartsWith("Failed") && authenticationID != "") { string uploadResult = uploadPicture(authenticationID, sfAppID, myDateTaken, moveToPath, newFileName.ToString(), ext); if (uploadResult.StartsWith("Failed")) { uploadErrors.Add(pictureFile.Name); } } else { uploadErrors.Add(pictureFile.Name); } } } else { moveErrors.Add(pictureFile.Name); moveToManualFolder(pictureFile.FullName, importDir, newFileName.ToString(), ext); } result = "Successfully moved file " + pictureFile.Name + " to " + moveToPath + " as " + newFileName.ToString() + ext; }
//private static string sendEmail(List<string> moveErrors, List<string> uploadErrors) //{ // try // { // string smtpServer = ConfigurationManager.AppSettings["smtpServer"].ToString(); // string fromEmail = ConfigurationManager.AppSettings["fromEmail"].ToString(); // string eFromPsswd = ConfigurationManager.AppSettings["fromPsswd"].ToString(); // SecureString securedPsswd = Encrypting.DecryptString(eFromPsswd); // string toEmail = ConfigurationManager.AppSettings["adminEmail"].ToString(); // MailMessage msg = new MailMessage(); // msg.IsBodyHtml = true; // msg.From = new MailAddress(fromEmail); // msg.To.Add(new MailAddress(toEmail)); // msg.Subject = "PicImp error moving or uploading"; // StringBuilder sb = new StringBuilder(); // if (moveErrors.Count > 0) // { // sb.AppendLine("Error moving the following files:"); // foreach (string mError in moveErrors) // { // sb.AppendLine("\t" + mError); // } // } // if (uploadErrors.Count > 0) // { // sb.AppendLine("Error uploading the following files:"); // foreach (string uError in uploadErrors) // { // sb.AppendLine("\t" + uError); // } // } // string body = System.Net.WebUtility.HtmlEncode(sb.ToString()); // //HTML encode does not modify whitespace // body = body.Replace("\n", "<br>"); // body = body.Replace("\t", " "); // msg.Body = body; // SmtpClient smtp = new SmtpClient // { // Host = smtpServer, // Port = 587, // EnableSsl = true, // UseDefaultCredentials = false, // Credentials = new System.Net.NetworkCredential(fromEmail, Encrypting.ToInsecureString(securedPsswd)) // }; // smtp.Send(msg); // return "true"; // } // catch (Exception ex) // { // return ex.ToString(); // } //} private void processVideo(FileInfo videoFile, string prefix, string suffix, bool useCameraMake, ref List <string> moveErrors) { DateTime myDateTaken = videoFile.CreationTime; string ext = videoFile.Extension.ToLower(); StringBuilder newFileName = new StringBuilder(); newFileName.Append(prefix); newFileName.Append(myDateTaken.ToString("yyyyMMdd_HHmmss")); newFileName.Append(suffix); Bitmap bmp; try { bmp = new Bitmap(videoFile.FullName); } catch { moveErrors.Add(videoFile.Name); //moveToManualFolder(videoFile.FullName, importDir, newFileName.ToString(), ext); return; } EXIFextractor exif = new EXIFextractor(ref bmp, "n"); // get source from http://www.codeproject.com/KB/graphics/exifextractor.aspx?fid=207371 if (useCameraMake) { string cameraModel = GetCameraModel(exif); if (cameraModel != "") { newFileName.Append("_"); newFileName.Append(cameraModel); } } string moveToPath = CreateVidDirStructure(ref myDateTaken); //Attempt to move if (moveToPath != "Error") { try { string result = moveVideo(videoFile.FullName, moveToPath, newFileName.ToString(), ext); if (result == "Error") { moveErrors.Add(videoFile.Name); moveToManualFolder(videoFile.FullName, importDir, newFileName.ToString(), ext); } } catch { moveErrors.Add(videoFile.Name); moveToManualFolder(videoFile.FullName, importDir, newFileName.ToString(), ext); } } else { moveErrors.Add(videoFile.Name); moveToManualFolder(videoFile.FullName, importDir, newFileName.ToString(), ext); } }