private static ImageInfo GetInfoFromJpgExifReader(Stream stream) { stream.Seek(0, SeekOrigin.Begin); // Set curser back to start var exif = new ExifLib.ExifReader(stream); var res = new ImageInfo(); if (exif.GetTagValue(ExifLib.ExifTags.ImageWidth, out uint w1)) { res.Width = (int)w1; } else if (exif.GetTagValue(ExifLib.ExifTags.PixelXDimension, out uint w2)) { res.Width = (int)w2; } if (exif.GetTagValue(ExifLib.ExifTags.ImageLength, out uint h1)) { res.Height = (int)h1; } else if (exif.GetTagValue(ExifLib.ExifTags.PixelYDimension, out uint h2)) { res.Height = (int)h2; } //if (exif.GetTagValue(ExifLib.ExifTags.BitsPerSample, out uint b1) && b1 > 0) { // res.BitsPerChannel = (int)b1; //} else if (exif.GetTagValue(ExifLib.ExifTags.SamplesPerPixel, out uint b2) && b2 > 0) { // res.BitsPerChannel = (int)b2; //} else if (exif.GetTagValue(ExifLib.ExifTags.CompressedBitsPerPixel, out uint b3) && b3 > 0) { // res.BitsPerChannel = (int)b3; //} else if (exif.GetTagValue(ExifLib.ExifTags.Compression, out uint b4) && b4 > 0) { // res.BitsPerChannel = (int)b4; //} return(res); }
//retrieves the datetime WITHOUT loading the whole image public static DateTime GetDateTakenFromImage(string path) { DateTime date = DateTime.Now; string ext = Path.GetExtension(path); try { if (ext.ToLower() == ".jpg" || ext.ToLower() == ".jpeg") { using (ExifLib.ExifReader reader = new ExifLib.ExifReader(path)) { // Extract the tag data using the ExifTags enumeration reader.GetTagValue<DateTime>(ExifLib.ExifTags.DateTimeDigitized, out date); } if (date.Year > DateTime.Now.Year || date.Year < 1980) { date = File.GetLastWriteTime(path); } } else if (ext.ToLower() == ".png" || ext.ToLower() == ".mov") { date = File.GetLastWriteTime(path); } } catch(Exception ex) { //MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } return date; }
protected byte[] ResizeImage(byte[] image, int maxHeight = 360) { byte[] dc; System.Drawing.Image oBMP = null; using (var ms = new MemoryStream(image)) { oBMP = System.Drawing.Image.FromStream(ms); ms.Close(); } UInt16 orientCode = 1; try { using (var ms2 = new MemoryStream(image)) { var r = new ExifLib.ExifReader(ms2); r.GetTagValue(ExifLib.ExifTags.Orientation, out orientCode); } } catch { } int nHeight = maxHeight; // This is 36x10 line:7700 GenScreen int nWidth = int.Parse((Math.Round(decimal.Parse(oBMP.Width.ToString()) * (nHeight / decimal.Parse(oBMP.Height.ToString())))).ToString()); var nBMP = new System.Drawing.Bitmap(oBMP, nWidth, nHeight); using (System.IO.MemoryStream sm = new System.IO.MemoryStream()) { // 1 = do nothing if (orientCode == 3) { // rotate 180 nBMP.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); } else if (orientCode == 6) { //rotate 90 nBMP.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone); } else if (orientCode == 8) { // same as -90 nBMP.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone); } nBMP.Save(sm, System.Drawing.Imaging.ImageFormat.Jpeg); sm.Position = 0; dc = new byte[sm.Length + 1]; sm.Read(dc, 0, dc.Length); sm.Close(); } oBMP.Dispose(); nBMP.Dispose(); return(dc); }
protected override void SpecificProcessing() { IExtractor <Image> extractor = ExtractorFactory.CreateExtractor("coordinates"); foreach (var item in _filesInfo) { using (Image img = Image.FromFile(item)) { //var data = extractor.Extract(img, 0).Split(' '); ExifLib.ExifReader reader = new ExifLib.ExifReader(item); double lat; reader.GetTagValue(ExifLib.ExifTags.GPSLatitude, out lat); double lon; reader.GetTagValue(ExifLib.ExifTags.GPSLongitude, out lon); //double alt = Double.Parse( data[0]); //double lon = Double.Parse(data[1]); } } }
public IEnumerable <IImageInfo> Parse(string rootDirPath) { var files = Directory.GetFiles(rootDirPath, "*.jpg", SearchOption.AllDirectories); foreach (var file in files) { var reader = new ExifLib.ExifReader(file); reader.GetTagValue(ExifLib.ExifTags.DateTimeOriginal, out string result); yield return(new ImageInfo() { CapturedOn = ToDateTime(result), FileDetails = new FileInfo(file) }); } }
private DateTime GetCreationDate(Stream imageData) { DateTime creationDate; // Using ExifLib to read creationDate. Not using `using` on purpose, because then ExifReader disposes `photo` as well. var reader = new ExifLib.ExifReader(imageData); // Found by experimenting that WP-made photos have DateTimeOriginal set. Good enough! reader.GetTagValue <DateTime>(ExifLib.ExifTags.DateTimeOriginal, out creationDate); // rewind stream. imageData.Seek(0, SeekOrigin.Begin); return(creationDate); }
private static void PrintSupportedExifInfo(ExifLib.ExifReader reader) { foreach (ExifLib.ExifTags t in GetEnumValues <ExifLib.ExifTags>()) { object value; try { if (reader.GetTagValue(t, out value)) { System.Diagnostics.Debug.WriteLine(t.ToString() + " = " + value.ToString() + " (" + value.GetType().ToString() + ")"); } } catch (Exception ex) { } } }
public ParseResult Parse(string pathfile) { string model = null; using (var reader = new ExifLib.ExifReader(pathfile)) { reader.GetTagValue <string>(ExifLib.ExifTags.Model, out model); } var xml = new XDocument( new XElement("exif", new XAttribute("model", model ?? "null") ) ); return(ParseResult.Create( Name, xml)); }
private void TryReadExifInfo(Stream stream) { using (var reader = new ExifLib.ExifReader(stream)) { PrintSupportedExifInfo(reader); // Aperture double aperture; if (reader.GetTagValue(ExifLib.ExifTags.FNumber, out aperture)) { Infos.Add(new Info() { Title = AppResources.InfoPage_ApertureTitleTextBlock_Text, Value = "F" + Math.Round(aperture, 1).ToString().Replace(',', '.') }); } // Exposure time double exposureTime; if (reader.GetTagValue(ExifLib.ExifTags.ExposureTime, out exposureTime)) { Infos.Add(new Info() { Title = AppResources.InfoPage_ExposureTimeTitleTextBlock_Text, Value = String.Format(AppResources.InfoPage_ExposureTimeValueFormatTextBlock_Text, Math.Round(exposureTime, 2).ToString()) }); } // ISO UInt16 iso; if (reader.GetTagValue(ExifLib.ExifTags.ISOSpeedRatings, out iso) && iso > 0) { Infos.Add(new Info() { Title = AppResources.InfoPage_IsoTitleTextBlock_Text, Value = iso.ToString() }); } // Flash (simplified) UInt16 flash; if (reader.GetTagValue(ExifLib.ExifTags.Flash, out flash)) { var bytes = BitConverter.GetBytes(flash); Infos.Add(new Info() { Title = AppResources.InfoPage_FlashTitleTextBlock_Text, Value = (bytes[0] & 0x01) != 0x00 ? AppResources.InfoPage_FlashValueFiredTextBlock_Text : AppResources.InfoPage_FlashValueNotFiredTextBlock_Text }); } // Date and time DateTime dateTime; if (reader.GetTagValue(ExifLib.ExifTags.DateTimeOriginal, out dateTime)) { Infos.Add(new Info() { Title = AppResources.InfoPage_DateTimeTitleTextBlock_Text, Value = dateTime.ToLocalTime().ToString() }); } // Dimensions UInt32 x; UInt32 y; if (reader.GetTagValue(ExifLib.ExifTags.PixelXDimension, out x) && x > 0 && reader.GetTagValue(ExifLib.ExifTags.PixelYDimension, out y) && y > 0) { Infos.Add(new Info() { Title = AppResources.InfoPage_DimensionsTitleTextBlock_Text, Value = x + " x " + y }); } // Make string make; if (reader.GetTagValue(ExifLib.ExifTags.Make, out make) && make.Length > 0) { Infos.Add(new Info() { Title = AppResources.InfoPage_MakeTitleTextBlock_Text, Value = make }); } // Model string model; if (reader.GetTagValue(ExifLib.ExifTags.Model, out model) && model.Length > 0) { Infos.Add(new Info() { Title = AppResources.InfoPage_ModelTitleTextBlock_Text, Value = model }); } // Software string software; if (reader.GetTagValue(ExifLib.ExifTags.Software, out software) && software.Length > 0) { Infos.Add(new Info() { Title = AppResources.InfoPage_SoftwareTitleTextBlock_Text, Value = software }); } } }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.BelowNormal; try { ImageCodecInfo jpegEncoder = GetEncoder(ImageFormat.Jpeg); string name = string.Format(Properties.Settings.Default.Name, DateTime.Now); foreach (string image in srcImages) { // Trouver le chemin exact string path = System.IO.Path.GetDirectoryName(image); string deltaPath = path.Substring(Properties.Settings.Default.Src.Length); FileInfo fiSrc = new FileInfo(image); string finalName = System.IO.Path.GetFileNameWithoutExtension(image) + ".rc" + System.IO.Path.GetExtension(image); string dest = Properties.Settings.Default.Dest + "\\" + name + "\\" + deltaPath + "\\" + finalName; DateTime date = fiSrc.LastWriteTime; try { using (ExifLib.ExifReader reader = new ExifLib.ExifReader(image)) { DateTime date2; reader.GetTagValue <DateTime>(ExifLib.ExifTags.DateTimeDigitized, out date2); if (date2 != DateTime.MinValue) { date = date2; } } } catch { } if (btnReorganise.Checked) { dest = Properties.Settings.Default.Dest + string.Format("\\{0:0000}{1:00}\\{2}", date.Year, date.Month, finalName); } uData.CDInterface.CreateDirectoryForFile(dest); bool bRecompress = true; if (System.IO.File.Exists(dest)) { bRecompress = false; } if (bRecompress) { try { Image bmp = Bitmap.FromFile(image); List <PropertyItem> items = new List <PropertyItem>(bmp.PropertyItems); Bitmap tmp = new Bitmap(bmp); foreach (PropertyItem item in items) { tmp.SetPropertyItem(item); } System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, Convert.ToInt64(Properties.Settings.Default.JPEGQuality)); myEncoderParameters.Param[0] = myEncoderParameter; try { tmp.Save(dest, jpegEncoder, myEncoderParameters); } catch { } finally { if (!System.IO.File.Exists(dest)) { System.IO.File.Copy(image, dest); } } tmp.Dispose(); bmp.Dispose(); FileInfo fiDest = new FileInfo(dest); fiDest.CreationTime = date; fiDest.LastAccessTime = date; fiDest.LastWriteTime = date; } catch (Exception ex) { MessageBox.Show(string.Format("Erreur {0}\r\nsur l'image {1}", ex.Message, image)); bRecompress = false; } } if (bRecompress) { finalSize += GetFileSize(dest); processed.Add(image); } backgroundWorker1.ReportProgress(0); if (backgroundWorker1.CancellationPending) { e.Cancel = true; break; } } if (!e.Cancel) { foreach (string movie in srcMovies) { FileInfo fiSrc = new FileInfo(movie); // Trouver le chemin exact string path = System.IO.Path.GetDirectoryName(movie); string deltaPath = path.Substring(Properties.Settings.Default.Src.Length); string finalName = System.IO.Path.GetFileNameWithoutExtension(movie) + ".rc" + destFormatMovie; string dest = Properties.Settings.Default.Dest + "\\" + name + "\\" + deltaPath + "\\" + finalName; if (btnReorganise.Checked) { dest = Properties.Settings.Default.Dest + string.Format("\\{0:0000}{1:00}\\{2}", fiSrc.LastWriteTime.Year, fiSrc.LastWriteTime.Month, finalName); } uData.CDInterface.CreateDirectoryForFile(dest); if (!System.IO.File.Exists(dest)) { System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = AppDomain.CurrentDomain.BaseDirectory + "ffmpeg.exe"; process.StartInfo.Arguments = string.Format("-vsync 2 -y -i \"{0}\" \"{1}\"", movie, dest); process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized; process.Start(); process.WaitForExit(); if (System.IO.File.Exists(dest)) { FileInfo fiDest = new FileInfo(dest); fiDest.CreationTimeUtc = fiSrc.CreationTimeUtc; fiDest.LastAccessTimeUtc = fiSrc.LastAccessTimeUtc; fiDest.LastWriteTimeUtc = fiSrc.LastWriteTimeUtc; } else { System.IO.File.Copy(movie, dest); } } finalSize += GetFileSize(dest); processed.Add(movie); backgroundWorker1.ReportProgress(0); if (backgroundWorker1.CancellationPending) { e.Cancel = true; break; } } } if (!e.Cancel) { System.Diagnostics.Process.Start("explorer.exe", Properties.Settings.Default.Dest + "\\" + name); } } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (!e.Cancel) { if (Properties.Settings.Default.EraseSource) { foreach (string image in srcImages) { System.IO.File.Delete(image); } foreach (string movie in srcMovies) { System.IO.File.Delete(movie); } } } } }
private static System.Drawing.Size GetImageSize(string directSourceLink, int maxDownloadBytes) { System.Drawing.Size result = new System.Drawing.Size(0, 0); try { HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create(directSourceLink); byte[] buffer = new byte[maxDownloadBytes]; wReq.UserAgent = "Other"; wReq.AddRange(0, buffer.Length); using (WebResponse wRes = wReq.GetResponse()) using (Stream stream = wRes.GetResponseStream()) { stream.Read(buffer, 0, buffer.Length); #region PNG if (buffer.Take(pngSignature.Length).SequenceEqual(pngSignature)) { var idhr = buffer.Skip(12); result.Width = BitConverter.ToInt32(idhr.Skip(4).Take(4).Reverse().ToArray(), 0); result.Height = BitConverter.ToInt32(idhr.Skip(8).Take(4).Reverse().ToArray(), 0); } #endregion #region BMP else if (buffer.Take(bmpSignature.Length).SequenceEqual(bmpSignature)) { var idhr = buffer.Skip(18); result.Width = BitConverter.ToInt32(idhr.Skip(0).Take(4).Reverse().ToArray(), 0); result.Height = BitConverter.ToInt32(idhr.Skip(4).Take(4).Reverse().ToArray(), 0); } #endregion #region JPG JFIF else if (buffer.Take(jpg1Signature.Length).SequenceEqual(jpg1Signature)) { if (maxDownloadBytes < readBytesForJpeg) { wRes.Close(); result = GetImageSize(directSourceLink, readBytesForJpeg); } else { using (MemoryStream fs = new MemoryStream(buffer)) { //skip signature fs.Seek(4, SeekOrigin.Begin); var buf = new byte[4]; long blockStart = fs.Position; fs.Read(buf, 0, 2); var blockLength = ((buf[0] << 8) + buf[1]); fs.Read(buf, 0, 4); if (Encoding.ASCII.GetString(buf, 0, 4) == "JFIF" && fs.ReadByte() == 0) { blockStart += blockLength; while (blockStart < fs.Length) { fs.Position = blockStart; fs.Read(buf, 0, 4); blockLength = ((buf[2] << 8) + buf[3]); if (blockLength >= 7 && buf[0] == 0xff && buf[1] == 0xc0) { fs.Position += 1; fs.Read(buf, 0, 4); result.Height = (buf[0] << 8) + buf[1]; result.Width = (buf[2] << 8) + buf[3]; break; } blockStart += blockLength + 2; } } } } } #endregion #region JPG EXIF else if (buffer.Take(jpg2Signature.Length).SequenceEqual(jpg2Signature)) { if (maxDownloadBytes < readBytesForJpeg) { wRes.Close(); result = GetImageSize(directSourceLink, readBytesForJpeg); } else { using (MemoryStream fs = new MemoryStream(buffer)) { //skip signature fs.Seek(4, SeekOrigin.Begin); var buf = new byte[4]; long blockStart = fs.Position; fs.Read(buf, 0, 2); var blockLength = ((buf[0] << 8) + buf[1]); fs.Read(buf, 0, 4); if (maxDownloadBytes >= blockLength + 10) { if (Encoding.ASCII.GetString(buf, 0, 4).ToUpper() == "EXIF" && fs.ReadByte() == 0) { using (MemoryStream ms = new MemoryStream(buffer)) using (ExifLib.ExifReader reader = new ExifLib.ExifReader(ms)) { System.UInt32 width; System.UInt32 height; reader.GetTagValue(ExifLib.ExifTags.PixelXDimension, out width); reader.GetTagValue(ExifLib.ExifTags.PixelYDimension, out height); result.Height = (int)height; result.Width = (int)width; } } } else { wRes.Close(); result = GetImageSize(directSourceLink, blockLength + 10); } } } } #endregion #region GIF else if (buffer.Take(gif1Signature.Length).SequenceEqual(gif1Signature) || buffer.Take(gif2Signature.Length).SequenceEqual(gif2Signature)) { var idhr = buffer.Skip(gif1Signature.Length); result.Width = idhr.ElementAt(0) | idhr.ElementAt(1) << 8; result.Height = idhr.ElementAt(2) | idhr.ElementAt(3) << 8; } #endregion } } catch (Exception ex) { Helpers.Old.Log.Add(ex, string.Format("Helper.GetImageSize('{0}',maxDownloadBytes:'{1}')", directSourceLink, maxDownloadBytes)); } return result; }