internal static BitmapSource ApplyOrientation(BitmapSource bitmap, BitmapMetadata metadata) { if (metadata == null || !metadata.ContainsQuery("System.Photo.Orientation")) return bitmap; ushort orientation = (ushort)metadata.GetQuery("System.Photo.Orientation"); switch (orientation) { case 2: // flip horizontal return new TransformedBitmap(bitmap, new ScaleTransform(-1, 1)); case 3: // rotate 180 return new TransformedBitmap(bitmap, new RotateTransform(-180)); case 4: // flip vertical return new TransformedBitmap(bitmap, new ScaleTransform(1, -1)); case 5: // transpose bitmap = new TransformedBitmap(bitmap, new ScaleTransform(1, -1)); goto case 8; case 6: // rotate 270 return new TransformedBitmap(bitmap, new RotateTransform(-270)); case 7: // transverse bitmap = new TransformedBitmap(bitmap, new ScaleTransform(-1, 1)); goto case 8; case 8: // rotate 90 return new TransformedBitmap(bitmap, new RotateTransform(-90)); default: return bitmap; } }
public void StripMeta(BitmapMetadata metaData) { for (int i = 270; i < 42016; i++) { if (i == 274 || i == 277 || i == 284 || i == 530 || i == 531 || i == 282 || i == 283 || i == 296) continue; string query = "/app1/ifd/exif:{uint=" + i + "}"; BlankMetaInfo(query, metaData); query = "/app1/ifd/exif/subifd:{uint=" + i + "}"; BlankMetaInfo(query, metaData); query = "/ifd/exif:{uint=" + i + "}"; BlankMetaInfo(query, metaData); query = "/ifd/exif/subifd:{uint=" + i + "}"; BlankMetaInfo(query, metaData); } for (int i = 0; i < 4; i++) { string query = "/app1/ifd/gps/{ulong=" + i + "}"; BlankMetaInfo(query, metaData); query = "/ifd/gps/{ulong=" + i + "}"; BlankMetaInfo(query, metaData); } }
private static decimal? ParseGpsVersion( BitmapMetadata metadata ) { var version = metadata.ReadUShortArray( GpsVersionQuery ); if( version == null ) { return null; } return version.Select( ( t, i ) => (decimal) Math.Pow( 10, -i ) * t ).Sum(); }
internal ExifGpsData Parse( BitmapMetadata metadata ) { return new ExifGpsData { GpsVersion = ParseGpsVersion( metadata ), ProcessingMethod = metadata.ReadString( ProcessingMethodQuery ), MeasureMode = ParseMeasureMode( metadata ), Latitude = ParseLatitude( metadata ), Longitude = ParseLongitude( metadata ), Altitude = ParseAltitude( metadata ) }; }
private static double? ParseAltitude( BitmapMetadata metadata ) { var altitude = metadata.ReadUnsignedRational( AltitudeQuery ); if( ! altitude.HasValue ) { return null; } var altitudeReference = metadata.ReadByte( AltitudeReferenceQuery ); if( altitudeReference.HasValue && altitudeReference.Value == 1 ) { altitude = -altitude; } return altitude; }
private static double? ParseCoordinate( BitmapMetadata metadata, string coordinateQuery, string directionQuery, string invertDirection ) { var coordinates = metadata.ReadULongArray( coordinateQuery ); if ( coordinates != null ) { var coordinate = ConvertCoordinate( coordinates ); var direction = metadata.ReadString( directionQuery ); if ( direction == invertDirection ) { coordinate = -coordinate; } return coordinate; } return null; }
private void BlankMetaInfo(string query, BitmapMetadata metaData) { object obj = metaData.GetQuery(query); if (obj != null) { if (obj is string) metaData.SetQuery(query, string.Empty); else { ulong dummy; if (ulong.TryParse(obj.ToString(), out dummy)) { metaData.SetQuery(query, 0); } } } }
// set up metadata private void SetUpMetadataOnImage(string filename, string[] tags) { // padding amount, using 2Kb. don't need much here; metadata is rather small uint paddingAmount = 2048; // open image file to read using (Stream file = File.Open(filename, FileMode.Open, FileAccess.Read)) { // create the decoder for the original file. The BitmapCreateOptions and BitmapCacheOption denote // a lossless transocde. We want to preserve the pixels and cache it on load. Otherwise, we will lose // quality or even not have the file ready when we save, resulting in 0b of data written BitmapDecoder original = BitmapDecoder.Create(file, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None); // create an encoder for the output file JpegBitmapEncoder output = new JpegBitmapEncoder(); // add padding and tags to the file, as well as clone the data to another object if (original.Frames[0] != null && original.Frames[0].Metadata != null) { // Because the file is in use, the BitmapMetadata object is frozen. // So, we clone the object and add in the padding. BitmapFrame frameCopy = (BitmapFrame)original.Frames[0].Clone(); BitmapMetadata metadata = original.Frames[0].Metadata.Clone() as BitmapMetadata; // we use the same method described in AddTags() as saving tags to save an amount of padding metadata.SetQuery("/app1/ifd/PaddingSchema:Padding", paddingAmount); metadata.SetQuery("/app1/ifd/exif/PaddingSchema:Padding", paddingAmount); metadata.SetQuery("/xmp/PaddingSchema:Padding", paddingAmount); // we add the tags we want as well. Again, using the same method described above metadata.SetQuery("System.Keywords", tags); // finally, we create a new frame that has all of this new metadata, along with the data that was in the original message output.Frames.Add(BitmapFrame.Create(frameCopy, frameCopy.Thumbnail, metadata, frameCopy.ColorContexts)); file.Close(); // close the file to ready for overwrite } // finally, save the new file over the old file // Essayer de créer un nouveau fichier puis supprimer l'autre !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! using (Stream outputFile = File.Open(filename, FileMode.Create, FileAccess.Write)) { output.Save(outputFile); } } }
} // Exists /// <summary> /// Устанавливает заданную маску индикатора языка ввода. /// </summary> /// <param name="maskBitmap">Маска-изображение, соответствующее подсвечиваемому языку ввода.</param> /// <param name="bounds">Положение маски на экране в экранных координатах.</param> public void SetMask(System.Drawing.Bitmap maskBitmap, System.Drawing.Rectangle bounds) { if (Path.GetExtension(MaskFileName).ToLower() != ".png") { throw new FileFormatException(new Uri(MaskFileName), $"Неподдерживаемое расширение файла {MaskFileName}. Предполагается расширение .png."); } if (Mask != null) { Mask.Dispose(); } if (MaskBitmap != null) { MaskBitmap.Dispose(); } MaskBitmap = maskBitmap; Mask = new Raster(MaskBitmap); Bounds = bounds; Debugger.Current?.TraceBounds(Bounds); Debugger.Current?.TraceMask(MaskBitmap); Debugger.Current?.TraceRaster(Mask); using (FileStream stream = File.Create(MaskFileName)) { PngBitmapEncoder encoder = new PngBitmapEncoder(); BitmapMetadata metadata = new BitmapMetadata("png"); metadata.SetQuery(BoundsMetadataQuery, $"{bounds.X},{bounds.Y}".ToCharArray()); BitmapFrame frame = BitmapFrame.Create(Mask.Source, null, metadata, null); encoder.Frames.Add(frame); encoder.Save(stream); /* * MaskBitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); * stream.Position = 0; * PngBitmapDecoder pngDecoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); * BitmapFrame frame = pngDecoder.Frames[0]; * InPlaceBitmapMetadataWriter inplaceMetadataWriter = frame.CreateInPlaceBitmapMetadataWriter(); * if (inplaceMetadataWriter.TrySave() == true) * { * inplaceMetadataWriter.SetQuery(BoundsMetadataQuery, $"{bounds.X},{bounds.Y}".ToCharArray()); * } */ } } // SetMask
private void SetMetadata(BitmapMetadata bitmapMetadata) { if (Caption != null) { bitmapMetadata.Comment = Caption; } //the rest is gps stuff if (GPSLatitude.HasValue && GPSLongitude.HasValue) { bitmapMetadata.SetQuery(GPSLatitudeQuery, ConvertCoordinate(GPSLatitude.Value)); bitmapMetadata.SetQuery(GPSLongitudeQuery, ConvertCoordinate(GPSLongitude.Value)); byte[] gpsVersionNumbers = new byte[4]; gpsVersionNumbers[0] = 0; gpsVersionNumbers[1] = 0; gpsVersionNumbers[2] = 2; gpsVersionNumbers[3] = 2; bitmapMetadata.SetQuery(GPSVersionIDQuery, gpsVersionNumbers); string northOrSouth = (GPSLatitude.Value >= 0) ? "N" : "S"; bitmapMetadata.SetQuery(GPSLatitudeRefQuery, northOrSouth); string eastOrWest = (GPSLongitude.Value >= 0) ? "E" : "W"; bitmapMetadata.SetQuery(GPSLongitudeRefQuery, eastOrWest); string gpsTime = GPSDateTime.Value.ToString("yyyy:MM:dd HH:mm:ss"); } else { bitmapMetadata.RemoveQuery(GPSLatitudeQuery); bitmapMetadata.RemoveQuery(GPSLongitudeQuery); bitmapMetadata.RemoveQuery(GPSLatitudeRefQuery); bitmapMetadata.RemoveQuery(GPSLongitudeRefQuery); } if (GPSDateTime.HasValue) { bitmapMetadata.SetQuery(GPSTimeStampQuery, ConvertGpsTime(GPSDateTime.Value)); bitmapMetadata.SetQuery(GPSDateStampQuery, ConvertGpsDate(GPSDateTime.Value)); } }
/// <summary> /// Метод возвращающий - Баланс белого /// </summary> /// <param name="TmpImgEXIF">Метаданные типа BitmapMetadata</param> /// <returns></returns> public string GetWhiteBalance(BitmapMetadata TmpImgEXIF) { try { int b = Convert.ToInt32(TmpImgEXIF.GetQuery("/app1/ifd/exif/{ushort=41987}")); // баланс белого -> 0 - это "авто", 1 - ручной баланс белого if (b == 0) { return("Авто"); } else { return("Ручной баланс белого"); } } catch (Exception) { return(""); } }
// Get metadata copyright public string getMetadataCopyright() { string copyright = null; BitmapMetadata mdtFile = getBitmapMetadataRead(); if (mdtFile != null) { copyright = mdtFile.Copyright; if (copyright == null) { this.addWarning("Le copyright n'est pas renseigné dans les métadonnées"); } } else { // Error this.addError("Une erreur est survenue lors de la lecture des métadonnées"); } return(copyright); }
public static void RemoveQuerySafe(this BitmapMetadata metadata, string query) { if (metadata == null || string.IsNullOrWhiteSpace(query)) { return; } try { if (metadata.ContainsQuery(query)) { metadata.RemoveQuery(query); } } catch (Exception ex) { Debug.WriteLine($"Exception while trying to remove metadata entry at position: {query}"); Debug.WriteLine(ex); } }
// Get metadata comment public string getMetadataComment() { string comment = ""; BitmapMetadata mdtFile = getBitmapMetadataRead(); if (mdtFile != null) { comment = mdtFile.Comment; if (comment == null) { this.addWarning("Les commentaires ne sont pas renseignés dans les métadonnées"); } } else { // Error this.addError("Une erreur est survenue lors de la lecture des métadonnées"); } return(comment); }
// Get metadata rate public int getMetadataRate() { int rate = 0; BitmapMetadata mdtFile = getBitmapMetadataRead(); if (mdtFile != null) { rate = mdtFile.Rating; if (rate < 0) { this.addWarning("La note n'est pas renseignée dans les métadonnées"); } } else { // Error this.addError("Une erreur est survenue lors de la lecture des métadonnées"); } return(rate); }
// Get metadata object public string getMetadataSubject() { string subject = null; BitmapMetadata mdtFile = getBitmapMetadataRead(); if (mdtFile != null) { subject = mdtFile.Subject; if (subject == null) { this.addWarning("L'objet n'est pas renseigné dans les métadonnées"); } } else { // Error this.addError("Une erreur est survenue lors de la lecture des métadonnées"); } return(subject); }
// Get Metadata DateTaken public string getMetadataDateTaken() { string dateTaken = ""; BitmapMetadata mdtFile = getBitmapMetadataRead(); if (mdtFile != null) { dateTaken = mdtFile.DateTaken; if (dateTaken == null) { this.addWarning("La date de prise de vu n'est pas renseignée dans les métadonnées"); } } else { // Error this.addError("Une erreur est survenue lors de la lecture des métadonnées"); } return(dateTaken); }
public static Rotation GetRotation(this BitmapMetadata metadata) { if (metadata.ContainsQuery(RotationQuery) && metadata.GetQuery(RotationQuery) is ushort rotationMetadata) { switch (rotationMetadata) { case 3: return(Rotation.Rotate180); case 6: return(Rotation.Rotate90); case 8: return(Rotation.Rotate270); } } return(Rotation.Rotate0); }
private void CopyStringTagTo(BitmapMetadata dst, string dstPropertyName, Metadata src, ExifTagID srcTagID) { PropertyItem[] pis = src.GetExifValues(srcTagID); if (pis.Length > 0) { PropertyInfo pi = dst.GetType().GetProperty(dstPropertyName); string piValue = Exif.DecodeAsciiValue(pis[0]); try { pi.SetValue(dst, piValue, null); } catch (Exception) { // *shrug* } } }
protected virtual void Dispose(bool disposing) { // Force Garbage ObjCollection GC.Collect(); GC.WaitForPendingFinalizers(); // Dispose of everything this.bitmapMetadata = null; this.bitmapDecoder = null; this.sourceStream.Close(); this.sourceStream.Dispose(); // If open for editing, delete the temporary file if (this.openForEditing && File.Exists(this.sourceFilename)) { File.Delete(this.sourceFilename); } this.disposed = true; }
private void BlankMetaInfo(string query, BitmapMetadata metaData) { object obj = metaData.GetQuery(query); if (obj != null) { if (obj is string) { metaData.SetQuery(query, string.Empty); } else { ulong dummy; if (ulong.TryParse(obj.ToString(), out dummy)) { metaData.SetQuery(query, 0); } } } }
// Get metadata title public string getMetadataTitle() { string title = null; BitmapMetadata mdtFile = getBitmapMetadataRead(); if (mdtFile != null) { title = mdtFile.Title; if (title == null) { this.addWarning("Le titre n'est pas renseigné dans les métadonnées"); } } else { // Error this.addError("Une erreur est survenue lors de la lecture des métadonnées"); } return(title); }
private void ButtonInsertClick(object sender, RoutedEventArgs e) { ImageBrush imgBrush = new ImageBrush(); imgBrush.ImageSource = new BitmapImage(new Uri(@"котэ с кентами.jpg", UriKind.RelativeOrAbsolute)); myRect.Fill = imgBrush; string title; using (FileStream stream = new FileStream(@"котэ с кентами.jpg", FileMode.OpenOrCreate)) { BitmapDecoder decoder = JpegBitmapDecoder.Create(stream, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.Default); BitmapMetadata metadata = (BitmapMetadata)decoder.Frames[0].Metadata; // Получаем заголовок через поле класса title = metadata.Title; } myLabel.Content = title; }
private WebPictureBasic GetWebPictureBasic(string path) { WebPictureBasic pic = new WebPictureBasic(); pic.Id = PathToId(path); pic.Path.Add(path); pic.Categories.Add(GetCategoryFromPath(path)); // Image metadata Uri uri = new Uri(path); if (!PathUtil.MightBeOnNetworkDrive(uri)) { try { BitmapSource img = BitmapFrame.Create(uri); BitmapMetadata meta = (BitmapMetadata)img.Metadata; if (!String.IsNullOrWhiteSpace(meta.Title)) { pic.Title = meta.Title.Trim(); } if (!String.IsNullOrWhiteSpace(meta.DateTaken)) { pic.DateTaken = DateTime.Parse(meta.DateTaken); } } catch (Exception ex) { Log.Error(String.Format("Error reading picture (meta-)data for {0}", path), ex); } } // Set title to file name if non-existant if (String.IsNullOrEmpty(pic.Title)) { pic.Title = Path.GetFileName(path); } return(pic); }
/// <summary> /// Load image from file. <br /> This one is fast. /// </summary> /// <param name="filepath"></param> /// <returns></returns> static public BitmapSource LoadThumbnail(String filepath, int pixelHeight = 90) { BitmapSource ret = null; BitmapMetadata meta = null; try { BitmapFrame frame = BitmapFrame.Create( new Uri(filepath), BitmapCreateOptions.DelayCreation, BitmapCacheOption.None); if (frame.Thumbnail == null) { BitmapImage image = new BitmapImage(); image.DecodePixelHeight = pixelHeight; image.BeginInit(); image.UriSource = new Uri(filepath); image.CacheOption = BitmapCacheOption.None; image.CreateOptions = BitmapCreateOptions.DelayCreation; image.EndInit(); if (image.CanFreeze) { image.Freeze(); } ret = image; } else { meta = frame.Metadata as BitmapMetadata; ret = frame.Thumbnail; } } catch (Exception) { } return(ret); }
private void ExtractExifData(BitmapMetadata data, Dictionary <string, object> dictionary) { if (data == null) { return; } foreach (var tag in data) { var query = data.GetQuery(tag); var bmp = query as BitmapMetadata; if (bmp != null) { ExtractExifData(bmp, dictionary); continue; } try { string name = tag; int index = tag.IndexOf('='); if (index >= 0) { name = tag.Substring(index + 1); name = name.Remove(name.IndexOf('}')); ushort value = 0; if (ushort.TryParse(name, out value)) { name = ((ExifTags)value).ToString(); } } dictionary[name] = query; } catch { dictionary[tag] = query; } } }
private static double?GetAltitude(BitmapMetadata bmpMetadata) { object altObj = GetQuery(bmpMetadata, "System.GPS.Altitude"); if (altObj == null) { altObj = GetQuery(bmpMetadata, @"/app1/ifd/gps/{ushort=6}"); if (altObj != null) { altObj = ConvertCoordinate(new ulong[] { (ulong)altObj })[0]; } } if (altObj == null) { return(null); } return(IsBelowSeaLevel(bmpMetadata) ? (double)altObj * (-1) : (double)altObj); }
private void PrintMetadata(System.Windows.Media.ImageMetadata metadata, string fullQuery) { BitmapMetadata theMetadata = metadata as BitmapMetadata; if (theMetadata != null) { foreach (string query in theMetadata) { string tempQuery = fullQuery + query; // query string here is relative to the previous metadata reader. object o = theMetadata.GetQuery(query); //richTextBox1.Text += "\n" + tempQuery + ", " + query + ", " + o; Console.WriteLine(tempQuery + ", " + query + ", " + o); BitmapMetadata moreMetadata = o as BitmapMetadata; if (moreMetadata != null) { PrintMetadata(moreMetadata, tempQuery); } } } }
private static ImageBehavior.FrameMetadata GetFrameMetadata(BitmapFrame frame) { BitmapMetadata metadata = (BitmapMetadata)frame.Metadata; TimeSpan timeSpan = TimeSpan.FromMilliseconds(100.0); int queryOrDefault1 = metadata.GetQueryOrDefault <int>("/grctlext/Delay", 10); if (queryOrDefault1 != 0) { timeSpan = TimeSpan.FromMilliseconds((double)(queryOrDefault1 * 10)); } ImageBehavior.FrameDisposalMethod queryOrDefault2 = (ImageBehavior.FrameDisposalMethod)metadata.GetQueryOrDefault <int>("/grctlext/Disposal", 0); return(new ImageBehavior.FrameMetadata() { Left = metadata.GetQueryOrDefault <int>("/imgdesc/Left", 0), Top = metadata.GetQueryOrDefault <int>("/imgdesc/Top", 0), Width = metadata.GetQueryOrDefault <int>("/imgdesc/Width", frame.PixelWidth), Height = metadata.GetQueryOrDefault <int>("/imgdesc/Height", frame.PixelHeight), Delay = timeSpan, DisposalMethod = queryOrDefault2 }); }
public PNGInfo GetObject(BitmapMetadata TmpImgEXIF, long length, string filename, string fullpath, string path) { return(new PNGInfo { FileDateCreated = GetFileCreated(path), FileDateModification = GetFileModification(path), FileSize = this.BytesToString(length), FileName = filename, FilePath = fullpath, FileImgSize = GetImageSize(path), FileType = "PNG", RedX = GetRedX(TmpImgEXIF), RedY = GetRedY(TmpImgEXIF), GreenX = GetGreenX(TmpImgEXIF), GreenY = GetGreenY(TmpImgEXIF), BlueX = GetBlueX(TmpImgEXIF), BlueY = GetBlueY(TmpImgEXIF), WhitePointX = GetWhitePointX(TmpImgEXIF), WhitePointY = GetWhitePointY(TmpImgEXIF) }); }
private static void CopySubIFDRecursive(ref BitmapMetadata parent, BitmapMetadata ifd, string query) { if (!parent.ContainsQuery(query)) { parent.SetQuery(query, new BitmapMetadata(ifd.Format)); } foreach (string tag in ifd) { object value = ifd.GetQuery(tag); if (value is BitmapMetadata ifdSub) { CopySubIFDRecursive(ref parent, ifdSub, query + tag); } else { parent.SetQuery(query + tag, value); } } }
private void GetInfo(object sender, MouseButtonEventArgs e) { Image image = sender as Image; string fileName = image.Source.ToString().Substring(8); FileInfo fileInfo = new FileInfo(fileName); FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); BitmapSource bitmapSource = BitmapFrame.Create(fileStream); BitmapMetadata bitmapMetadata = (BitmapMetadata)bitmapSource.Metadata; #region File TextBlockImageName.Text = fileInfo.Name; TextBlockImageFullName.Text = fileInfo.FullName; TextBlockImageSize.Text = $"{fileInfo.Length.ToString() } bytes"; TextBlockImageCreationDate.Text = fileInfo.CreationTimeUtc.ToString(); TextBlockImageModificationDate.Text = fileInfo.LastWriteTimeUtc.ToString(); #endregion #region Description TextBlockImageTitle.Text = bitmapMetadata.Title; TextBlockImageSubject.Text = bitmapMetadata.Subject; TextBlockImageComent.Text = bitmapMetadata.Comment; TextBlockImageTags.Text = ""; #endregion #region Image TextBlockImageCameraModel.Text = bitmapMetadata.CameraModel; TextBlockImageApertureUnit.Text = ""; TextBlockImageExposureTime.Text = ""; TextBlockImageFocalLenght.Text = ""; #endregion fileStream.Close(); fileStream.Dispose(); } //dodać obsługę wyciągania informacji z zdjęcia
public static void ReadWLPGRegions(string inputFile) { using (WpfFileManager wpfFileManager = new WpfFileManager(inputFile)) { // Declare a bunch of XMP paths (see my last blog for details) string microsoftRegions = @"/xmp/MP:RegionInfo/MPRI:Regions"; string microsoftPersonDisplayName = @"/MPReg:PersonDisplayName"; string microsoftRectangle = @"/MPReg:Rectangle"; // Check there is a RegionInfo if (wpfFileManager.BitmapMetadata.ContainsQuery(microsoftRegions)) { BitmapMetadata regionsMetadata = wpfFileManager.BitmapMetadata.GetQuery(microsoftRegions) as BitmapMetadata; // Loop through each Region foreach (string regionQuery in regionsMetadata) { string regionFullQuery = microsoftRegions + regionQuery; // Query for all the data for this region BitmapMetadata regionMetadata = wpfFileManager.BitmapMetadata.GetQuery(regionFullQuery) as BitmapMetadata; if (regionMetadata != null) { if (regionMetadata.ContainsQuery(microsoftPersonDisplayName)) { Console.WriteLine("PersonDisplayName:\t" + regionMetadata.GetQuery(XmpMicrosoftQueries.RegionPersonDisplayName.Query).ToString()); } if (regionMetadata.ContainsQuery(microsoftRectangle)) { Console.WriteLine("Rectangle:\t\t" + regionMetadata.GetQuery(XmpMicrosoftQueries.RegionRectangle.Query).ToString()); } } } } } }
/// <summary> /// 書き込みボタン /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_Click_5(object sender, RoutedEventArgs e) { if (GPSLatitudeRef == null) { MessageBox.Show("読み込んでから実行してください"); return; } // ファイル読みこみ MemoryStream data = new MemoryStream(File.ReadAllBytes(tb_FileName2.Text)); WriteableBitmap image = new WriteableBitmap(BitmapFrame.Create(data)); data.Close(); // metaデータを準備 var metadata = new BitmapMetadata("jpg"); metadata.SetQuery("/app1/ifd/gps/subifd:{ushort=1}", GPSLatitudeRef); metadata.SetQuery("/app1/ifd/gps/subifd:{ushort=2}", GPSLatitude); metadata.SetQuery("/app1/ifd/gps/subifd:{ushort=3}", GPSLongitudeRef); metadata.SetQuery("/app1/ifd/gps/subifd:{ushort=4}", GPSLongitude); metadata.SetQuery("/app1/ifd/{ushort=271}", "入れたメーカー名"); metadata.SetQuery("/app1/ifd/{ushort=272}", "いれたモデル名"); // ファイルに書き込み using (FileStream stream = new FileStream(tb_FileName2.Text, FileMode.Open)) { var enc = new JpegBitmapEncoder() { FlipHorizontal = false, FlipVertical = false, QualityLevel = 80, Rotation = Rotation.Rotate0 }; var frame = BitmapFrame.Create(image, null, metadata, null); enc.Frames.Add(frame); enc.Save(stream); } }
/// <summary> /// Изменение EXIF информации фотограйии для записи /// </summary> ///<param name="new_point">Координаты фотографии.</param> ///<param name="TmpImgEXIF">Ссылка на теги EXIF.</param> private void EditEXIF(PointGPS new_point, ref BitmapMetadata TmpImgEXIF) { //Запись в EXIF //широта if (new_point.latitude > 0) { //северная широта TmpImgEXIF.SetQuery("/app1/ifd/gps/{ushort=1}", "N"); } else { //южная широта TmpImgEXIF.SetQuery("/app1/ifd/gps/{ushort=1}", "S"); } //долгота if (new_point.longitude > 0) { //Восточная долгота TmpImgEXIF.SetQuery("/app1/ifd/gps/{ushort=3}", "E"); } else { //Западная долгота TmpImgEXIF.SetQuery("/app1/ifd/gps/{ushort=3}", "W"); } //Формат версии TmpImgEXIF.SetQuery("/app1/ifd/gps/{ushort=0}", "2.2.0.0"); //Высота ->6 TmpImgEXIF.SetQuery("/app1/ifd/gps/{ushort=6}", Rational(new_point.altitude)); //Широта конвертирование в градусы минуты секунды double Degree, Minute, Second; ConvertToDegreeMinuteSecond(new_point.latitude, out Degree, out Minute, out Second); ulong[] t = { Rational(Degree), Rational(Minute), Rational(Second) }; TmpImgEXIF.SetQuery("/app1/ifd/gps/{ushort=2}", t); //Долгота конвертирование в градусы минуты секунды ConvertToDegreeMinuteSecond(new_point.longitude, out Degree, out Minute, out Second); ulong[] t2 = { Rational(Degree), Rational(Minute), Rational(Second) }; TmpImgEXIF.SetQuery("/app1/ifd/gps/{ushort=4}", t2); }
/// <summary> /// /// </summary> /// <param name="fileName"></param> /// <exception cref="AgrumentException">Can't open file</exception> public EXIFFileWorker(string pathToFile) : this() { m_pathToFile = pathToFile; if (String.IsNullOrEmpty(pathToFile)) throw new ArgumentNullException("pathToFile"); if (!m_FileManager.Exists(pathToFile)) throw new ArgumentException("File not found", "pathToFile"); try { if (m_jpegStreamIn != null) m_jpegStreamIn .Close(); m_jpegStreamIn = m_FileManager.Open(pathToFile, FileMode.Open, FileAccess.Read); } catch (Exception e) { throw new ArgumentException("Can't open file", "pathToFile", e); } // unpack photo and make decoder m_Decoder = new JpegBitmapDecoder(m_jpegStreamIn, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None); m_Exif = (BitmapMetadata)m_Decoder.Frames[0].Metadata.Clone(); }
public static String GetTakenDate(string imagePath, Boolean withTime) { try { Uri imgUri = new Uri(imagePath); BitmapSource img = BitmapFrame.Create(imgUri); BitmapMetadata meta = (BitmapMetadata)img.Metadata; DateTime dateTime = DateTime.Parse(meta.DateTaken); if (withTime) { return(dateTime.ToString("yyyyMMdd_hhmmss")); } else { return(dateTime.ToString("yyyyMMdd")); } } catch (NotSupportedException) { return(null); } }
private static string[] montaListaComItensNovosEVelhos(string[] novosKeywords, BitmapMetadata metadata) { int tamanhoArray = novosKeywords.Length; if (metadata.Keywords != null) tamanhoArray += metadata.Keywords.Count; string[] keywords = new string[tamanhoArray]; int i = 0; if (metadata.Keywords != null) foreach (string keyword in metadata.Keywords) { keywords[i] = keyword; i++; } foreach (string tag in novosKeywords) { keywords[i] = tag; i++; } return keywords; }
public static void RemoveQuerySafe(this BitmapMetadata metadata, string query) { if (metadata == null || string.IsNullOrWhiteSpace(query)) { return; } try { if (metadata.ContainsQuery(query)) { metadata.RemoveQuery(query); } } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception ex) #pragma warning restore CA1031 // Do not catch general exception types { Debug.WriteLine($"Exception while trying to remove metadata entry at position: {query}"); Debug.WriteLine(ex); } }
internal BitmapFrameEncode( BitmapSource source, BitmapSource thumbnail, BitmapMetadata metadata, ReadOnlyCollection<ColorContext> colorContexts ) : base(true) { _bitmapInit.BeginInit(); Debug.Assert(source != null); _source = source; WicSourceHandle = _source.WicSourceHandle; IsSourceCached = _source.IsSourceCached; _isColorCorrected = _source._isColorCorrected; _thumbnail = thumbnail; _readOnlycolorContexts = colorContexts; InternalMetadata = metadata; _syncObject = source.SyncObject; _bitmapInit.EndInit(); FinalizeCreation(); }
public static void Save(Stream imageStream, BitmapMetadata metaData, Stream targetStream) { BitmapDecoder imgDecoder = BitmapDecoder.Create(imageStream, BitmapCreateOptions.None, BitmapCacheOption.Default); BitmapFrame img = imgDecoder.Frames[0]; var bmpEnc = new BmpBitmapEncoder(); if (metaData != null) { bmpEnc.Metadata = metaData; } else { bmpEnc.Metadata = imgDecoder.Metadata; } bmpEnc.Frames.Add(img); bmpEnc.Save(targetStream); GifBitmapEncoder gifEnc; JpegBitmapEncoder jpgEnc; PngBitmapEncoder pngEnc; TiffBitmapEncoder tiffEnc; WmpBitmapEncoder wmpEnc; }
public ExifMetadata(Uri imageUri) { var frame = BitmapFrame.Create(imageUri, BitmapCreateOptions.DelayCreation, BitmapCacheOption.None); _metadata = (BitmapMetadata) frame.Metadata; }
private static ExifGpsMeasureMode ParseMeasureMode( BitmapMetadata metadata ) { var measureMode = metadata.ReadByte( MeasureModeQuery ); return measureMode.HasValue ? (ExifGpsMeasureMode) measureMode.Value : ExifGpsMeasureMode.Unknown; }
public void CreateImageObject(string img, string filename) { _fp = new FileProperties(); _fs = new FileStream(img, FileMode.Open); _decoder = BitmapDecoder.Create(_fs, BitmapCreateOptions.None, BitmapCacheOption.Default); _frame = _decoder.Frames[0]; _metadata = _frame.Metadata as BitmapMetadata; if (_metadata != null && _metadata.DateTaken != null) { _fp.DateTaken = DateTime.Parse(_metadata.DateTaken); _fp.FullImagePath = img; } else { _fp.FullImagePath = img; } _fp.FileName = filename; _fp.FolderPath = Path.GetDirectoryName(img); _theImages.Add(_fp); _fs.Close(); }
public static System.Windows.Media.Imaging.BitmapFrame Create(BitmapSource source, BitmapSource thumbnail, BitmapMetadata metadata, System.Collections.ObjectModel.ReadOnlyCollection<System.Windows.Media.ColorContext> colorContexts) { return default(System.Windows.Media.Imaging.BitmapFrame); }
/// <summary> /// Populates keywords: /// <ul> /// <li/>Takes the EXIF keywords from the passed metadata /// <li/>Generates EXIF keywords from the path_ /// <li/>Normalizes the newly generated keywords - only first letter is Capital /// <li/>Normalization is executed - if the flag is switched on /// </ul> /// </summary> /// <param name="metaData_">Metadata</param> /// <param name="applyNormalization_">Flag if normalization should be applied or not</param> /// <param name="path_">Path of the file to be processed</param> /// <param name="keywords_">Extra keywords</param> /// <returns></returns> public static HashSet<string> populateKeywords(BitmapMetadata metaData_, bool applyNormalization_, string path_ , IEnumerable<string> keywords_ ) { HashSet<string> lst = new HashSet<string>(); if (metaData_.Keywords != null) { lst = new HashSet<string>(metaData_.Keywords); } if (keywords_ != null) { foreach (string key in keywords_) { lst.Add(key); } } if (path_ != null) { IEnumerable<string> patternKeys = applyPatternsOnPath(path_, ' '); foreach (string keyword in patternKeys) { lst.Add(keyword); } } var arr = capitalizeFirstLetter(lst); lst.Clear(); Array.ForEach(arr, c => lst.Add(c)); lst.Add(Constants.PROGRAM_TAG_SIGNATURE); if(applyNormalization_) { foreach (string[] normalizationEntry in Constants.NORMALIZATION_DICT) { string badKey = normalizationEntry[0]; string correctKey = normalizationEntry[1]; string[] lst_arr = new string[lst.Count]; lst.CopyTo(lst_arr); for(int i=lst_arr.Length-1; i>0;i--) { string key = lst_arr[i]; if (match(key, badKey) != null) { lst.Remove(key); //if correctKey is defined then it should be added if (correctKey != null) { lst.Add(correctKey); } } } } } return lst; }
private static double? ParseLongitude( BitmapMetadata metadata ) { return ParseCoordinate( metadata, LongitudeQuery, EastOrWestQuery, "W" ); }
private static double? ParseLatitude( BitmapMetadata metadata ) { return ParseCoordinate( metadata, LatitudeQuery, NorthOrSouthQuery, "S" ); }
void generateImageCollage() { ItemProgressMax = 100; ItemProgress = 0; //ItemInfo = "Creating video preview image for: " + System.IO.Path.GetFileName(item.Location); FileStream outputFile = null; RenderTargetBitmap bitmap = null; try { JpegBitmapEncoder encoder = new JpegBitmapEncoder(); BitmapMetadata metaData = new BitmapMetadata("jpg"); metaData.ApplicationName = App.getAppInfoString(); metaData.DateTaken = DateTime.Now.ToString("R"); int? maxGridHeight = AsyncState.IsMaxGridHeightEnabled ? new Nullable<int>(AsyncState.MaxGridHeight) : null; App.Current.Dispatcher.Invoke(() => { PictureGridImage gridImage = new PictureGridImage(AsyncState, AsyncState.Media.ToList(), AsyncState.IsUseThumbs); bitmap = gridImage.createGridImage(AsyncState.MaxWidth, maxGridHeight); }); encoder.Frames.Add(BitmapFrame.Create(bitmap, null, metaData, null)); String outputPath = AsyncState.OutputPath + "\\" + AsyncState.Filename + ".jpg"; outputFile = new FileStream(outputPath, FileMode.Create); encoder.QualityLevel = AsyncState.JpegQuality; encoder.Save(outputFile); ItemProgress = ItemProgressMax; TotalProgress = TotalProgressMax; InfoMessages.Add("Finished image collage: " + outputPath); } catch (Exception e) { InfoMessages.Add("Error creating image collage: " + e.Message); Logger.Log.Error("Error creating image collage: ", e); } finally { if (bitmap != null) { bitmap.Clear(); bitmap = null; } if (outputFile != null) { outputFile.Close(); } // because of the extreme amount of memory used by rendertargetbitmap // make sure we have it all back before moving on to prevent out of memory spikes GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } }
private int GetRotation(BitmapMetadata metadata) { int rotation = 0; if ((metadata != null) && metadata.ContainsQuery("System.Photo.Orientation")) { object o = metadata.GetQuery("System.Photo.Orientation"); if (o != null) { //refer to http://www.impulseadventure.com/photo/exif-orientation.html for details on orientation values switch ((ushort)o) { case 6: rotation = 90; break; case 3: rotation = 180; break; case 8: rotation = 270; break; } } } return rotation; }
private void SetRotation(BitmapMetadata metadata, int rotation) { if (metadata == null) throw new ArgumentNullException("metadata"); int value = 1; switch(rotation) { case 0: value = 1; break; case 90: value = 6; break; case 180: value = 3; break; case 270: value = 8; break; default: throw new ArgumentException("rotation"); } metadata.SetQuery("System.Photo.Orientation", value); }
private static void AddIptcMetadata(BitmapMetadata bmpMetadata, IGalleryObjectMetadataItemCollection metadataItems) { foreach (KeyValuePair<FormattedMetadataItemName, string> iptcQueryParm in GetIptcQueryParameters()) { string iptcValue = bmpMetadata.GetQuery(String.Format(CultureInfo.InvariantCulture, IptcQueryFormatString, iptcQueryParm.Value)) as string; if (!String.IsNullOrEmpty(iptcValue)) { switch (iptcQueryParm.Key) { case FormattedMetadataItemName.IptcDateCreated: { DateTime dateTaken = TryParseDate(iptcValue); if (dateTaken.Year > DateTime.MinValue.Year) { metadataItems.AddNew(int.MinValue, iptcQueryParm.Key, GetResource(iptcQueryParm.Key), dateTaken.ToString(DateTimeFormatStringForMetadata, CultureInfo.InvariantCulture), true); } break; } default: { metadataItems.AddNew(int.MinValue, iptcQueryParm.Key, GetResource(iptcQueryParm.Key), iptcValue, true); break; } } } } }
/// <summary> /// Attach a keyword to an image by overwriting. /// </summary> private static void AttachImageKeyword(string p_filePath, string p_keyword) { // must be done by creating a new image with the appropriate metadata string tempPath = Path.GetDirectoryName(p_filePath) + @"\" + Path.GetFileNameWithoutExtension(p_filePath) + " TEMP.jpg"; try { File.Move(p_filePath, tempPath); } catch (Exception ex) { Utility.LogRight.WriteLog("Couldn't create temp file: " + p_filePath); throw ex; } File.Delete(p_filePath); FileStream tempStream = new FileStream(tempPath, FileMode.Open, FileAccess.ReadWrite); JpegBitmapEncoder encoder = new JpegBitmapEncoder(); JpegBitmapDecoder decoder = new JpegBitmapDecoder(tempStream, BitmapCreateOptions.None, BitmapCacheOption.Default); BitmapMetadata myBitmapMetadata = new BitmapMetadata("jpg"); try { // this property is Keywords in XP, but Tags in windows 7 explorer myBitmapMetadata.Keywords = new ReadOnlyCollection<string>(new List<string>() { p_keyword }); } catch (Exception ex) { Utility.LogRight.WriteLog("Couldn't attach keyword to: " + p_filePath); throw ex; } // Create a new frame that is identical to the one from the original image, except for the new metadata. encoder.Frames.Add( BitmapFrame.Create(decoder.Frames[0], decoder.Frames[0].Thumbnail, myBitmapMetadata, decoder.Frames[0].ColorContexts)); FileStream createStream = new FileStream(p_filePath, FileMode.Create); encoder.Save(createStream); createStream.Close(); tempStream.Close(); try { File.Delete(tempPath); } catch //(Exception ex) { System.Threading.Thread.SpinWait(500); // stupid fix for bullshit windows system File.Delete(tempPath); } }
/// <summary> /// Adds GPS data from the <paramref name="bmpMetadata" /> to the <paramref name="metadataItems" /> collection. /// </summary> /// <param name="bmpMetadata">An object containing the metadata.</param> /// <param name="metadataItems">The metadata items.</param> private static void AddGpsMetadata(BitmapMetadata bmpMetadata, IGalleryObjectMetadataItemCollection metadataItems) { GpsLocation gps = GpsLocation.Parse(bmpMetadata); if (!String.IsNullOrEmpty(gps.Version)) { metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsVersion, GetResource(FormattedMetadataItemName.GpsVersion), gps.Version, true); } if ((gps.Latitude != null) && (gps.Longitude != null)) { metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsLocation, GetResource(FormattedMetadataItemName.GpsLocation), gps.ToLatitudeLongitudeDecimalString(), true); metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsLatitude, GetResource(FormattedMetadataItemName.GpsLatitude), gps.Latitude.ToDouble().ToString("F6", CultureInfo.InvariantCulture), true); metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsLongitude, GetResource(FormattedMetadataItemName.GpsLongitude), gps.Longitude.ToDouble().ToString("F6", CultureInfo.InvariantCulture), true); } if (gps.Altitude.HasValue) { string altitude = String.Concat(gps.Altitude.Value.ToString("N0", CultureInfo.CurrentCulture), " ", Resources.Metadata_meters); metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsAltitude, GetResource(FormattedMetadataItemName.GpsAltitude), altitude, true); } if ((gps.DestLatitude != null) && (gps.DestLongitude != null)) { metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsDestLocation, GetResource(FormattedMetadataItemName.GpsDestLocation), gps.ToDestLatitudeLongitudeDecimalString(), true); metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsDestLatitude, GetResource(FormattedMetadataItemName.GpsDestLatitude), gps.DestLatitude.ToDouble().ToString("F6", CultureInfo.InvariantCulture), true); metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsDestLongitude, GetResource(FormattedMetadataItemName.GpsDestLongitude), gps.DestLongitude.ToDouble().ToString("F6", CultureInfo.InvariantCulture), true); } }
private void EnsureMetadata(bool createBitmapMetadata) { if (!_supportsGlobalMetadata) { return; } if (_metadataHandle == null) { SafeMILHandle /* IWICMetadataQueryWriter */ metadataHandle = new SafeMILHandle(); int hr = UnsafeNativeMethods.WICBitmapEncoder.GetMetadataQueryWriter( _encoderHandle, out metadataHandle ); if (hr == (int)WinCodecErrors.WINCODEC_ERR_UNSUPPORTEDOPERATION) { _supportsGlobalMetadata = false; return; } HRESULT.Check(hr); _metadataHandle = metadataHandle; } if (createBitmapMetadata && _metadata == null && _metadataHandle != null) { _metadata = new BitmapMetadata(_metadataHandle, false, IsMetadataFixedSize, _metadataHandle); } }
/* public Location ParseLocationData() { return ...; } public int GetPictureId() { return ...; } public List<Tag> GetTags() { return ...; } */ private void GetBitmapMetadata() { FileInfo f = new FileInfo(picturePath); FileStream fs = new FileStream(f.FullName, FileMode.Open, FileAccess.Read, FileShare.Read); BitmapSource img = BitmapFrame.Create(fs); metadata = (BitmapMetadata)img.Metadata; }
public static Rotation? getOrientationFromMetatdata(BitmapMetadata meta) { if (meta != null) { UInt16 orientation = 1; Object result = meta.GetQuery("/app1/ifd/{ushort=274}"); if (result != null) { orientation = (UInt16)result; } else { return (null); } switch (orientation) { case 8: return (Rotation.Rotate270); case 3: return (Rotation.Rotate180); case 6: return (Rotation.Rotate90); default: return (Rotation.Rotate0); } } else { return (null); } }
/// <summary> /// Returns the metadata for the given query. /// </summary> /// <param name="metadata">The image metadata.</param> /// <param name="query">A list of query strings.</param> /// <returns>Metadata object or null if the metadata is not found.</returns> private static object GetMetadataObject(BitmapMetadata metadata, params string[] query) { foreach (string q in query) { object val = metadata.GetQuery(q); if (val != null) return val; } return null; }
static void CreatePng(TileSetLoader loader, string dstPath) { int numSymbols = EnumHelpers.GetEnumMax<SymbolID>() + 1; int[] tileSizes = new int[] { 8, 10, 12, 16, 20, 24, 32, 40, 48, 64, 80, 96 }; int maxTileSize = tileSizes.Max(); WriteableBitmap target = new WriteableBitmap(tileSizes.Sum(), maxTileSize * numSymbols, 96, 96, PixelFormats.Bgra32, null); target.Lock(); // leave the first one (Undefined) empty for (int i = 1; i < numSymbols; ++i) { int xOffset = 0; foreach (int tileSize in tileSizes) { var source = loader.GetTileBitmap((SymbolID)i, tileSize); int stride = source.PixelWidth * (source.Format.BitsPerPixel / 8); byte[] data = new byte[stride * source.PixelHeight]; source.CopyPixels(data, stride, 0); target.WritePixels(new Int32Rect(xOffset, i * maxTileSize, tileSize, tileSize), data, stride, 0); xOffset += tileSize; } } target.Unlock(); string tileSizesStr = string.Join(",", tileSizes.Select(i => i.ToString())); var pngEncoder = new PngBitmapEncoder(); var metadata = new BitmapMetadata("png"); metadata.SetQuery("/tEXt/Software", "Dwarrowdelf"); metadata.SetQuery("/tEXt/tilesizes", tileSizesStr); var frame = BitmapFrame.Create(target, null, metadata, null); pngEncoder.Frames = new BitmapFrame[] { frame }; string path = Path.Combine(dstPath, "TileSet.png"); using (var stream = File.OpenWrite(path)) pngEncoder.Save(stream); Console.WriteLine("Generated TileSet to {0}", path); }
/// <summary> /// Read metadata via WIC/WPF. /// </summary> /// <param name="data">metadata</param> private void InitViaWpf(BitmapMetadata data) { Object val; // Subject val = GetMetadataObject(data, WICPathImageDescription); if (val != null) ImageDescription = val as string; // Copyright val = GetMetadataObject(data, WICPathCopyright); if (val != null) Copyright = val as string; // Comment val = GetMetadataObject(data, WICPathComment); if (val != null) Comment = val as string; // Software val = GetMetadataObject(data, WICPathSoftware); if (val != null) Software = val as string; // Simple rating val = GetMetadataObject(data, WICPathSimpleRating); if (val != null) { ushort simpleRating = Convert.ToUInt16(val); if (simpleRating == 1) Rating = 1; else if (simpleRating == 2) Rating = 25; else if (simpleRating == 3) Rating = 50; else if (simpleRating == 4) Rating = 75; else if (simpleRating == 5) Rating = 99; } // Rating val = GetMetadataObject(data, WICPathRating); if (val != null) Rating = (int)Convert.ToUInt16(val); // Authors val = GetMetadataObject(data, WICPathArtist); if (val != null) { if (val is string) Artist = (string)val; else if (val is System.Collections.Generic.IEnumerable<string>) { int i = 0; StringBuilder authors = new StringBuilder(); foreach (string author in (System.Collections.Generic.IEnumerable<string>)val) { if (i != 0) authors.Append(";"); authors.Append(authors); i++; } Artist = authors.ToString(); } } // Camera manufacturer val = GetMetadataObject(data, WICPathEquipmentManufacturer); if (val != null) EquipmentManufacturer = val as string; // Camera model val = GetMetadataObject(data, WICPathEquipmentModel); if (val != null) EquipmentModel = val as string; // Date taken val = GetMetadataObject(data, WICPathDateTaken); if (val != null) DateTaken = ExifDateTime((string)val); // Exposure time val = GetMetadataObject(data, WICPathExposureTime); if (val != null) ExposureTime = ExifDouble(BitConverter.GetBytes((ulong)val)); // FNumber val = GetMetadataObject(data, WICPathFNumber); if (val != null) FNumber = ExifDouble(BitConverter.GetBytes((ulong)val)); // ISOSpeed val = GetMetadataObject(data, WICPathISOSpeed); if (val != null) ISOSpeed = Convert.ToUInt16(val); // FocalLength val = GetMetadataObject(data, WICPathFocalLength); if (val != null) FocalLength = ExifDouble(BitConverter.GetBytes((ulong)val)); }