当前位置: 首页>>代码示例>>C#>>正文


C# Bitmap.GetPropertyItem方法代码示例

本文整理汇总了C#中System.Drawing.Bitmap.GetPropertyItem方法的典型用法代码示例。如果您正苦于以下问题:C# Bitmap.GetPropertyItem方法的具体用法?C# Bitmap.GetPropertyItem怎么用?C# Bitmap.GetPropertyItem使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Drawing.Bitmap的用法示例。


在下文中一共展示了Bitmap.GetPropertyItem方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetDateTaken

 static DateTime GetDateTaken(string fileName)
 {
     Console.ResetColor();
     Console.Write($"Reading {fileName} date ");
     try
     {
         using (var image = new Bitmap(fileName))
         {
             var dateItem = image.GetPropertyItem(0x9003);
             if (dateItem != null)
             {
                 var dateText = Encoding.ASCII.GetString(dateItem.Value);
                 var dateTaken = DateTime.ParseExact(dateText, "yyyy:MM:dd HH:mm:ss\0", CultureInfo.InvariantCulture);
                 Console.ForegroundColor = ConsoleColor.Yellow;
                 Console.WriteLine("[EXIF]");
                 return dateTaken;
             }
         }
     }
     catch
     {
         Console.ForegroundColor = ConsoleColor.Red;
         Console.WriteLine("[Last Write]");
     }
     Console.ResetColor();
     return File.GetLastWriteTime(fileName);
 }
开发者ID:diegose,项目名称:MediaImport,代码行数:27,代码来源:Importer.cs

示例2: Load

        public static LCDBitmapAnimation Load(Bitmap img)
        {
            LCDBitmapAnimation anim = new LCDBitmapAnimation();
            anim.FrameHeight = img.Height;
            anim.FrameWidth = img.Width;

            int fcount = img.GetFrameCount(FrameDimension.Time);
            if (fcount == 1)
            {
                anim.Frames.Add(LCDBitmap.Load(img));
                anim.FrameTimes.Add(1);
            }
            else
            {
                byte[] times = img.GetPropertyItem(0x5100).Value;
                for (int i = 0; i < fcount; i++)
                {
                    img.SelectActiveFrame(FrameDimension.Time, i);
                    int dur = BitConverter.ToInt32(times, (i * 4) % times.Length) * 10;
                    anim.FrameTimes.Add(dur);
                    anim.Frames.Add(LCDBitmap.Load(img));
                }
            }

            anim.Length = anim.FrameTimes.Sum();

            return anim;
        }
开发者ID:Bzaraticus,项目名称:WiringPi,代码行数:28,代码来源:LCDBitmapAnimation.cs

示例3: PostDecodeStream

        protected override RequestedAction PostDecodeStream(ref Bitmap b, ResizeSettings settings)
        {
            if (!"true".Equals(settings["autorotate"], StringComparison.OrdinalIgnoreCase)) return RequestedAction.None;

            int propertyId = 0x0112;
            PropertyItem pi;
            try {
                pi = b.GetPropertyItem(propertyId);
            } catch (ArgumentException) {
                return RequestedAction.None;
            }
            if (pi == null) return RequestedAction.None;

            int total = 0;

            foreach (byte by in pi.Value) total += by; //Does not handle values larger than 255, but it doesn't need to, and is endian-agnostic.

            if (total == 8) b.RotateFlip(RotateFlipType.Rotate270FlipNone);
            if (total == 3) b.RotateFlip(RotateFlipType.Rotate180FlipNone);
            if (total == 6) b.RotateFlip(RotateFlipType.Rotate90FlipNone);

            if (total == 2) b.RotateFlip(RotateFlipType.RotateNoneFlipX);
            if (total == 4) b.RotateFlip(RotateFlipType.Rotate180FlipX);
            if (total == 5) b.RotateFlip(RotateFlipType.Rotate270FlipY);
            if (total == 7) b.RotateFlip(RotateFlipType.Rotate90FlipY);

            b.RemovePropertyItem(propertyId);

            return RequestedAction.None;
        }
开发者ID:stukalin,项目名称:ImageResizer,代码行数:30,代码来源:AutoRotate.cs

示例4: rotatePhotos

        private void rotatePhotos(object parameters)
        {
            object[] paramsArray = (object[])parameters;
            List<string> fileNames = (List<string>)paramsArray[0];
            PointF rotationCenter = (PointF)paramsArray[1];
            Bitmap referencePic = new Bitmap(fileNames.First());
            Image<Bgr, Byte> referenceImage = new Image<Bgr, Byte>(referencePic);

            byte[] timeTakenRaw = referencePic.GetPropertyItem(36867).Value;
            string timeTaken = System.Text.Encoding.ASCII.GetString(timeTakenRaw, 0, timeTakenRaw.Length - 1);
            DateTime referenceTime = DateTime.ParseExact(timeTaken, "yyyy:MM:d H:m:s", System.Globalization.CultureInfo.InvariantCulture);

            referencePic.Dispose();

            Bgr background = new Bgr(0, 0, 0);

            foreach (string filename in fileNames)
            {
                Bitmap currentPic = new Bitmap(filename);
                timeTakenRaw = currentPic.GetPropertyItem(36867).Value;
                timeTaken = System.Text.Encoding.ASCII.GetString(timeTakenRaw, 0, timeTakenRaw.Length - 1);
                DateTime date = DateTime.ParseExact(timeTaken, "yyyy:MM:d H:m:s", System.Globalization.CultureInfo.InvariantCulture);
                double secondsShift = (date - referenceTime).TotalSeconds;
                double rotationAngle = secondsShift / stellarDay * 360;
                RotationMatrix2D<double> rotationMatrix = new RotationMatrix2D<double>(rotationCenter, -rotationAngle, 1);

                using (Image<Bgr, Byte> rotatedImage = new Image<Bgr, Byte>(currentPic))
                {
                    referenceImage = referenceImage.Max(rotatedImage.WarpAffine<double>(rotationMatrix, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC, Emgu.CV.CvEnum.WARP.CV_WARP_FILL_OUTLIERS, background));
                }
                pictureProcessed(this, new PictureProcessedEventArgs(referenceImage));
                currentPic.Dispose();
            }
            pictureProcessingComplete(this, new EventArgs());
        }
开发者ID:jorik041,项目名称:StarStacker,代码行数:35,代码来源:ThreadWorker.cs

示例5: GetLocationTaken

        public string GetLocationTaken()
        {
            Image picture = new Bitmap(@"C:\Users\Brandon\Pictures\2 Months\20141208_152422.jpg");

            //Property Item 0x0002 corresponds to the Date Taken
            PropertyItem propItemRef = picture.GetPropertyItem(1);
            PropertyItem propItem = picture.GetPropertyItem(2);

            //Convert date taken metadata to a DateTime object
            double coordinates = ExifGpsToFloat(propItemRef, propItem);
            return coordinates.ToString();

            /*    string sdate = Encoding.UTF8.GetString(propItem.Value).Trim();
            dtaken = float.Parse(sdate);

            // Get the PropertyItems property from image.
            PropertyItem[] propItems = image.PropertyItems;

            // Set up the display.
            Font font = new Font("Arial", 12);
            SolidBrush blackBrush = new SolidBrush(Color.Black);
            int X = 0;
            int Y = 0;

            // For each PropertyItem in the array, display the ID, type, and
            // length.
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            int count = 0;
            foreach (PropertyItem propItem in propItems)
            {
                dataOutputLabel.Text +=
                    "Property Item " + count.ToString() + ": " + encoding.GetString(propItem.Value).ToString() + "\n"
                    + "iD: 0x" + propItem.Id.ToString("x") + "\n"
                    + "type: " + propItem.Type.ToString() + "\n"
                    + "length: " + propItem.Len.ToString() + " bytes" + "\n\n";

                count++;
            } */
        }
开发者ID:ratRenRao,项目名称:PhotoOrganizer,代码行数:39,代码来源:PictureData.cs

示例6: Main

 static void Main(string[] args)
 {
     if (args.Length > 0)
     {
         try
         {
             string path = args[0];
             Bitmap bitmap = new Bitmap(path);
             string value = Encoding.Default.GetString(bitmap.GetPropertyItem(0x0132).Value);
             bool flag = true;
             if (value.Length < 7)
             {
                 flag = false;
             }
             else if (!isNumber(value[0]) || !isNumber(value[1]) || !isNumber(value[2]) || !isNumber(value[3]))
             {
                 flag = false;
             }
             else if (isNumber(value[4]))
             {
                 flag = false;
             }
             else if (!isNumber(value[5]) || !isNumber(value[6]))
             {
                 flag = false;
             }
             if (flag)
             {
                 value = value.Substring(0, 4) + "-" + value.Substring(5, 2);
                 Console.WriteLine(value);
             }
             else
             {
                 Console.WriteLine(-1);
             }
         }
         catch
         {
             Console.WriteLine(-1);
         }
     }
     else
     {
         Console.WriteLine(-1);
     }
 }
开发者ID:hhh920406,项目名称:Typewriter,代码行数:46,代码来源:Program.cs

示例7: ScanDirectory

		/// <summary>
		/// Сканирует папку в поисках фотографий и добавляет их в коллекцию
		/// </summary>
		/// <param name="directory">Папка</param>
		private void ScanDirectory(string directory)
		{ 
			// Находим все файлы с расширением .jpg
			string[] fileNames = Directory.GetFiles(path, "*.jpg");

			var encoding = new ASCIIEncoding();

			foreach (string fileName in fileNames)
			{
				Image photo = new Bitmap(fileName);
				
				DateTime date = DateTime.MinValue;

				try
				{
					// Из спецификации стандарта EXIF http://www.exif.org/Exif2-2.PDF
					// 4.6.5 Exif IFD Attribute Information из стандарта EXIF
					// id = 36868 - дата съемки
					string dateString = encoding.GetString(photo.GetPropertyItem(36868).Value).TrimEnd('\0');

					date = DateTime.ParseExact(dateString, DATE_TIME_FORMAT, null);
				}
				catch
				{
					// В случае ошибки считывания даты из фотографии, пропускаем её
					continue;
				}
				finally
				{
					if(photo != null)
						photo.Dispose();
				}

				// Добавляем фото в коллекцию
				photos.Add(new Photo() { Path = fileName, Date = date });
			}
		}
开发者ID:SlidEnergy,项目名称:PhotoOrganizer,代码行数:41,代码来源:PhotoEditor.cs

示例8: SetExifInformation

        public static void SetExifInformation(Bitmap bitmap, XmlDocument imageMetaData)
        {
            if((bitmap != null)&&(imageMetaData != null))
            {
                foreach(PropertyItem pi in bitmap.PropertyItems)
                {
                    switch(pi.Id)
                    {
                        case 0x2: // GPSLatitude

                            PropertyItem gpsLatRef = bitmap.GetPropertyItem(0x1);

                            double lat = ExifGpsToDouble(gpsLatRef, pi);
                            if(lat != 0)
                            {
                                SetMetadata("GPSLatitude", lat.ToString(), imageMetaData);
                            }
                            else
                            {
                                SetMetadata("GPSLatitude", string.Empty, imageMetaData);
                            }

                            break;
                        case 0x4: // GPSLongitude

                            PropertyItem gpsLongRef = bitmap.GetPropertyItem(0x3);

                            double longi = ExifGpsToDouble(gpsLongRef, pi);
                            if(longi != 0)
                            {
                                SetMetadata("GPSLongitude", longi.ToString(), imageMetaData);
                            }
                            else
                            {
                                SetMetadata("GPSLongitude", string.Empty, imageMetaData);
                            }

                            break;
                        case 0x6: // GPSAltitude

                            int alti = BitConverter.ToInt32(pi.Value,0);

                            SetMetadata("GPSAltitude", alti.ToString(), imageMetaData);

                            break;

                        //case 0x1B: //GPSProcessingMethod
                        //    SetMetadata("GPSProcessingMethod", ConvertByteArrayToString(pi.Value), imageMetaData);
                        //    break;
                        //case 0x1C: //GPSAreaInfo
                        //    SetMetadata("GPSAreaInfo", ConvertByteArrayToString(pi.Value), imageMetaData);
                        //    break;

                        case 0x010F:
                            SetMetadata("EquipMake", ConvertByteArrayToString(pi.Value), imageMetaData);
                            break;
                        case 0x0110:
                            SetMetadata("EquipModel", ConvertByteArrayToString(pi.Value), imageMetaData);
                            break;
                        case 0x0112:
                        switch(ConvertByteArrayToShort(pi.Value))
                        {
                            case 1:
                                SetMetadata("Orientation", "upper left", imageMetaData);
                                break;
                            case 2:
                                SetMetadata("Orientation", "upper right", imageMetaData);
                                break;
                            case 3:
                                SetMetadata("Orientation", "lower right", imageMetaData);
                                break;
                            case 4:
                                SetMetadata("Orientation", "lower left", imageMetaData);
                                break;
                            case 5:
                                SetMetadata("Orientation", "upper left flipped", imageMetaData);
                                break;
                            case 6:
                                SetMetadata("Orientation", "upper right flipped", imageMetaData);
                                break;
                            case 7:
                                SetMetadata("Orientation", "lower right flipped", imageMetaData);
                                break;
                            case 8:
                                SetMetadata("Orientation", "lower left flipped", imageMetaData);
                                break;
                        }
                            break;
                        case 0x011a:
                            SetMetadata("XResolution", ConvertByteArrayToRational(pi.Value), imageMetaData);
                            break;
                        case 0x011b:
                            SetMetadata("YResolution", ConvertByteArrayToRational(pi.Value), imageMetaData);
                            break;
                        case 0x0128:
                            SetMetadata("ResolutionUnit", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData);
                            break;
                        case 0x0132:
                            SetMetadata("Datetime", ConvertByteArrayToString(pi.Value), imageMetaData);
                            break;
//.........这里部分代码省略.........
开发者ID:saiesh86,项目名称:TravelBlog,代码行数:101,代码来源:ImageHelper.cs

示例9: Build

        private void Build()
        {
            try
            {
                if (sourceGallery == null)
                {
                    sourceGallery = new Gallery { Categories = new List<Category>() };
                }

                var gallery = new Gallery { Categories = new List<Category>() };

                var startTime = DateTime.Now;
                var year = 0;
                var folders = sourceFolder.GetDirectories();

                var thumbnailMaxWidth = ConfigurationManager.ThumbnailBuilderConfiguration.ThumbnailMaxWidth;
                var thumbnailMaxHeight = ConfigurationManager.ThumbnailBuilderConfiguration.ThumbnailMaxHeight;
                var photoMaxWidth = ConfigurationManager.ThumbnailBuilderConfiguration.PhotoMaxWidth;
                var photoMaxHeight = ConfigurationManager.ThumbnailBuilderConfiguration.PhotoMaxHeight;

                var photosPath = Path.Combine(DirectoryHelper.GetSolutionDirectoryPath(AppDomain.CurrentDomain.BaseDirectory), ConfigurationManager.ThumbnailBuilderConfiguration.TargetFolderPath);

                foreach (var folder in folders)
                {
                    var files = folder.GetFiles("*.jpg", SearchOption.AllDirectories);
                    var folderName = folder.Name;
                    var photoId = 0;
                    var category = new Category
                    {
                        Photos = new List<Photo>()
                    };

                    var name = GetNameWithoutDateInfo(folderName);

                    if (IsExistInGallery(name))
                    {
                        for (var i = 0; i < files.Length; i++)
                        {
                            this.InvokeProcessBar();
                        }
                        continue;
                    }

                    if (files.Length <= 0)
                    {
                        break;
                    }

                    try
                    {
                        var image = new Bitmap(files[0].FullName);
                        var propertyItem = image.GetPropertyItem(0x132);
                        var dateString = Encoding.UTF8.GetString(propertyItem.Value, 0, propertyItem.Value.Length - 1);
                        var date = DateTime.ParseExact(dateString, "yyyy:MM:dd HH:mm:ss", CultureInfo.InvariantCulture);
                        year = date.Year;
                        category.Date = date.ToString("yyyy-MM-dd");
                        image.Dispose();
                    }
                    catch (ArgumentException)
                    {
                        year = files[0].LastWriteTime.Year;
                        category.Date = files[0].LastWriteTime.ToString("yyyy-MM-dd");
                    }
                    catch (Exception)
                    {
                        category.Date = DateTime.MinValue.ToString("yyyy-MM-dd");
                        year = 0;
                    }

                    category.Year = year;
                    category.Name = name;
                    gallery.Categories.Add(category);

                    foreach (var file in files)
                    {


                        var thumbnailFileNameWithFolder = year + file.FullName.Substring(sourceFolder.FullName.Length, file.FullName.Length - sourceFolder.FullName.Length);
                        var thumbnailFullPath = Path.Combine(photosPath, thumbnailFolder, thumbnailFileNameWithFolder);
                        var thumbnailPhotoInfo = ImageHelper.GetThumbnail(thumbnailMaxWidth, thumbnailMaxHeight, file.FullName, thumbnailFullPath, false);
                        var normalFileNameWithFolder = year + file.FullName.Substring(sourceFolder.FullName.Length, file.FullName.Length - sourceFolder.FullName.Length);
                        var normalFullPath = Path.Combine(photosPath, normalFolder, normalFileNameWithFolder);
                        var normalPhotoInfo = ImageHelper.GetThumbnail(photoMaxWidth, photoMaxHeight, file.FullName, normalFullPath, false);

                        photoId++;
                        var photo = new Photo
                            {
                                Id = photoId,
                                Title = Path.GetFileNameWithoutExtension(file.FullName),
                                Height = normalPhotoInfo.Height,
                                Width = normalPhotoInfo.Width,
                                NormalUrl = "/Resources/images/photos/" + normalFolder + "/" + StringHelper.GetUriFromPath(normalFileNameWithFolder),
                                ThumbnailUrl = "/Resources/images/photos/" + thumbnailFolder + "/" + StringHelper.GetUriFromPath(thumbnailFileNameWithFolder)
                            };

                        category.Photos.Add(photo);
                        this.InvokeProcessBar();
                    }
                }

//.........这里部分代码省略.........
开发者ID:Benguan,项目名称:M3,代码行数:101,代码来源:MainForm.cs

示例10: ApplyChanges

        /// <summary>
        /// Apply changes.
        /// </summary>
        public void ApplyChanges()
        {
            var data                     = File.ReadAllBytes(FilePath);
              var originalBinaryDataStream = new MemoryStream(data);
              var image                    = new Bitmap(originalBinaryDataStream);

              try {
            foreach (var propItem in image.PropertyItems) { // PropertyItem
              if (HasRecordingDate()) {
            var recording   = image.GetPropertyItem((int)ImagePropertyKey.RECORDING);
            recording.Value = _encoding.GetBytes(RecordingDate.ToString("yyyy:MM:dd HH:mm:ss", CultureInfo.CurrentCulture));
            image.SetPropertyItem(recording);
            var shooting1   = image.GetPropertyItem((int)ImagePropertyKey.SHOOTING1);
            shooting1.Value = _encoding.GetBytes(ShootingDate.ToString("yyyy:MM:dd HH:mm:ss", CultureInfo.CurrentCulture));
            image.SetPropertyItem(shooting1);
            var shooting2   = image.GetPropertyItem((int)ImagePropertyKey.SHOOTING2);
            shooting2.Value = _encoding.GetBytes(ShootingDate.ToString("yyyy:MM:dd HH:mm:ss", CultureInfo.CurrentCulture));
            image.SetPropertyItem(shooting2);
              }
            }

            image.Save(FilePath);
              } finally {
            image.Dispose();
            originalBinaryDataStream.Dispose();
              }
        }
开发者ID:devpro,项目名称:Wpf-Picture-Organizer,代码行数:30,代码来源:PictureFile.cs

示例11: upload_Click

        protected void upload_Click(object sender, EventArgs e)
        {
            string filepath = txt_fileUpLoad.Text;
            title = tbTitle.Text.ToString();
            desc = tbDescription.Text.ToString();

            if (fileUpLoad.HasFile)
            {
                string fileType = Path.GetExtension(filepath);
                if (fileType == ".avi")
                {
                    //Get the address
                    address = tbLocation.Text.ToString();
                    //double lng = Double.Parse(tbX.Text.ToString());
                    //double lat = Double.Parse(tbY.Text.ToString());
                    //string convert = CoordinatesConverter.CoordinatesConvertor(lng, lat, 4326, 3414);
                    //string[] converting = convert.Split(',');
                    //x = Double.Parse(converting[0]);
                    //y = Double.Parse(converting[1]);

                    //Get the video filename for analysis
                    type = "Video";
                    strVideoPath = fileUpLoad.PostedFile.FileName.ToString();
                    savePath = Server.MapPath("~\\video\\");
                    fileUpLoad.PostedFile.SaveAs(savePath + strVideoPath);
                    path = savePath + strVideoPath;
                    FileInfo oFileInfo = new FileInfo(path);
                    if (oFileInfo != null || oFileInfo.Length == 0)
                    {
                        date = oFileInfo.CreationTime;
                    }
                    AviManager aviManager = new AviManager(path, true);
                    AudioStream audioStream = aviManager.GetWaveStream();
                    audioStream.ExportStream(path + ".wav");
                    vfilepath = path + ".wav";
                    aviManager.Close();
                    soundAnalysis();
                    grabVideo(path);
                    //videoAnalysis();
                    //insertIntoDatabase();
                }
                else if (fileType == ".jpg")
                {
                    type = "Image";
                    txt_fileUpLoad.Text = "";
                    strVideoPath = fileUpLoad.PostedFile.FileName.ToString();
                    savePath = Server.MapPath("~\\image\\");
                    fileUpLoad.PostedFile.SaveAs(savePath + strVideoPath);
                    Bitmap pic = new Bitmap(savePath + strVideoPath);
                    property_ids = pic.PropertyIdList;

                    foreach (int scan_property in property_ids)
                    {
                        byte_property_id = pic.GetPropertyItem(scan_property).Value;
                        prop_type = pic.GetPropertyItem(scan_property).Type.ToString();

                        if (scan_property == 2)
                        {
                            //Latitude degrees minutes and seconds (rational)
                            degrees = System.BitConverter.ToInt32(byte_property_id, 0) / System.BitConverter.ToInt32(byte_property_id, 4);
                            minutes = System.BitConverter.ToInt32(byte_property_id, 8) / System.BitConverter.ToInt32(byte_property_id, 12);
                            seconds = System.BitConverter.ToInt32(byte_property_id, 16) / System.BitConverter.ToInt32(byte_property_id, 20);

                            lat_dd = degrees + (minutes / 60) + (seconds / 3600); //->Latitude
                        }
                        else if (scan_property == 4)
                        {
                            //Longitude degrees minutes and seconds (rational)
                            degrees = System.BitConverter.ToInt32(byte_property_id, 0) / System.BitConverter.ToInt32(byte_property_id, 4);
                            minutes = System.BitConverter.ToInt32(byte_property_id, 8) / System.BitConverter.ToInt32(byte_property_id, 12);
                            seconds = System.BitConverter.ToInt32(byte_property_id, 16) / System.BitConverter.ToInt32(byte_property_id, 20);
                            long_dd = degrees + (minutes / 60) + (seconds / 3600); //-->longtitude
                        }
                        else
                        {
                            //Do nothing...
                            /**
                            if (scan_property == 24)
                            {
                                //Magnetic bearing of subject to photographer (rational)
                                //do nothing
                            }
                            //scan_property ++;
                             * **/
                        }
                    }
                }
                if ((lat_dd > 0) && (long_dd > 0))
                {
                    //Reverse Geocoding
                    XmlDocument doc = new XmlDocument();
                    doc.Load("http://maps.googleapis.com/maps/api/geocode/xml?latlng=" + lat_dd + "," + long_dd + "&sensor=false");
                    XmlNode element = doc.SelectSingleNode("//GeocodeResponse/status");
                    if (element.InnerText == "ZERO_RESULTS")
                    {
                        lb_msg.Text = "No result found";
                    }
                    else
                    {
                        element = doc.SelectSingleNode("//GeocodeResponse/result/formatted_address");
//.........这里部分代码省略.........
开发者ID:hzhiguang,项目名称:AbuseAnalysis,代码行数:101,代码来源:share.aspx.cs

示例12: CopyWithOffsetFiles

        private void CopyWithOffsetFiles(string from, string to, int hours, int minutes, int years, int months, int days)
        {
            string[] files = Directory.GetFiles(from);
            List<FileInfo> filesFI = files.Select(s => new FileInfo(s)).ToList();

            foreach (var file in filesFI)
            {
                string saveTO = to + "\\" + Guid.NewGuid().ToString();

                try
                {
                    Bitmap image = new Bitmap(file.FullName);
                    PropertyItem propItem = image.GetPropertyItem(36867);

                    string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2);
                    DateTime dt = DateTime.Parse(dateTaken);

                    //dt = dt.AddHours(11).AddMinutes(23).AddYears(7).AddMonths(5).AddDays(-6);
                    dt = dt.AddHours(hours).AddMinutes(minutes).AddYears(years).AddMonths(months).AddDays(days);

                    byte[] aa = Encoding.UTF8.GetBytes(dt.ToString("yyyy:MM:dd HH:mm:ss") + "\0");
                    propItem.Value = aa;

                    image.SetPropertyItem(propItem);

                    image.Save(saveTO);
                    image.Dispose();
                    //f.CopyTo(to + (counter < 10 ? "0" + counter : counter.ToString()) + ".jpg");
                }
                catch
                {
                    Invoke(new MethodInvoker(delegate
                    {
                        lblError.Text = "Произашла ошибка при добавленни сдвига во времени, файлы с ошибками помечены как ERROR_0700.jpg";
                    }));
                    file.CopyTo(saveTO + "_ERROR");
                }

                Invoke(new MethodInvoker(delegate
                {
                    lblProgress.Text = mainText + " " + (filesFI.IndexOf(file) + 1) + "/" + filesFI.Count;
                    progressBar1.Value = (int)((Convert.ToDouble((filesFI.IndexOf(file) + 1)) / Convert.ToDouble(filesFI.Count)) * 1000);
                }));
            }
        }
开发者ID:targitaj,项目名称:m3utonetpaleyerxml,代码行数:45,代码来源:Form1.cs

示例13: Process

        private void Process()
        {
            if (!cbxOffset1.Checked)
            {
                mainText = "Копирование файлов из первой дирректории";
                CopyFiles(lblDir1.Text, lblDestDir.Text);
            }
            else
            {
                mainText = "Копирование файлов из первой дирректории и добавление сдвига";
                CopyWithOffsetFiles(lblDir1.Text, lblDestDir.Text, (int)nudHours1.Value, (int)nudMinutes1.Value,
                                   (int)nudYaer1.Value, (int)nudMonth1.Value, (int)nudDay1.Value);
            }

            if (!cbxOffset2.Checked)
            {
                mainText = "Копирование файлов из второй дирректории";
                CopyFiles(lblDir2.Text, lblDestDir.Text);
            }
            else
            {
                mainText = "Копирование файлов из второй дирректории и добавление сдвига";
                CopyWithOffsetFiles(lblDir2.Text, lblDestDir.Text, (int) nudHours2.Value, (int) nudMinutes2.Value,
                                    (int) nudYaer2.Value, (int) nudMonth2.Value, (int) nudDay2.Value);
            }

            string dir = lblDestDir.Text;
            string to = lblDestDir.Text + "\\";
            string[] files = Directory.GetFiles(dir);
            List<FileInfo> filesFI = files.Select(s => new FileInfo(s)).ToList();
            Dictionary<DateTime, FileInfo> res = new Dictionary<DateTime, FileInfo>();

            foreach (var f in filesFI)
            {
                Bitmap image = null;
                try
                {
                    image = new Bitmap(f.FullName);
                    PropertyItem propItem = image.GetPropertyItem(36867);

                    string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2);
                    DateTime dt = DateTime.Parse(dateTaken);

                    while (res.ContainsKey(dt))
                        dt = dt.AddSeconds(1);

                    res.Add(dt, f);

                    image.Dispose();
                }
                catch
                {
                    Invoke(new MethodInvoker(delegate
                    {
                        lblError.Text = "Произошла ошибка при сортировки, файлы с ошибками помечены как 0700_PR.jpg";
                    }));

                    string filePath = to + "_ERROR" + Guid.NewGuid().ToString();

                    if (image != null)
                        image.Dispose();
                    f.MoveTo(filePath);

                    DateTime lastDate = res.Last().Key.AddSeconds(1);

                    res.Add(lastDate, new FileInfo(filePath));
                }

                Invoke(new MethodInvoker(delegate
                {
                    lblProgress.Text = "Сортировка файлов " + (filesFI.IndexOf(f) + 1) + "/" + filesFI.Count;
                    progressBar1.Value = (int)((Convert.ToDouble((filesFI.IndexOf(f) + 1)) / Convert.ToDouble(filesFI.Count)) * 1000);
                }));
            }

            int counter = 1;

            filesFI = res.OrderBy(k => k.Key).Select(k => k.Value).ToList();

            foreach (var f in filesFI)
            {
                string saveTO = to + (counter < 10 ? "000" + counter : (counter < 100 ? "00" + counter : (counter < 1000 ? "0" + counter : counter.ToString()))) + (f.Name.Contains("_ERROR") ? "_PR" : "") + ".jpg";
                f.MoveTo(saveTO);
                counter++;

                Invoke(new MethodInvoker(delegate
                {
                    lblProgress.Text = "Переименование файлов " + (filesFI.IndexOf(f) + 1) + "/" + filesFI.Count;
                    progressBar1.Value = (int)((Convert.ToDouble((filesFI.IndexOf(f) + 1)) / Convert.ToDouble(filesFI.Count)) * 1000);
                }));
            }

            Invoke(new MethodInvoker(delegate
            {
                btnSplit.Text = "Соединить и отсортировать";
                lblProgress.Text = "Конец";
                progressBar1.Value = 0;
            }));
        }
开发者ID:targitaj,项目名称:m3utonetpaleyerxml,代码行数:99,代码来源:Form1.cs

示例14: SwitchToNextWallpaper

        private void SwitchToNextWallpaper()
        {
            _wallpaper.NextWallpaper(SetNotificationTooltip);
            _cts.Cancel();
            _cts = new CancellationTokenSource();
            var task = Task.Run(async () => await _wallpaper.Start(_cts.Token, SetNotificationTooltip));

            var filePath = @"C:\Users\ander\OneDrive\Pictures\Wallpaper - NSFW\102 - 424HMfp.jpg";
            using (var img = new Bitmap(filePath))
            {
                try
                {
                    var tag = img.GetPropertyItem(40094);
                    if (tag != null)
                    {
                        var foundTags = Encoding.Unicode.GetString(tag.Value).Replace("\0", string.Empty);
                    }
                }
                catch (ArgumentException)
                {
                }
            }

            using (var jpegStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                var decoder = BitmapDecoder.Create(jpegStream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                var jpegFrame = decoder.Frames[0];
                var metadata = (BitmapMetadata)jpegFrame.Metadata;
            }
        }
开发者ID:andersosthus,项目名称:WallpaperChanger,代码行数:30,代码来源:Main.cs

示例15: OnComboBoxImagesSelectedIndexChanged

        /// <summary>
        /// Displays the selected picture in the image area
        /// also displays the picture file name and Date Taken EXIF property
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnComboBoxImagesSelectedIndexChanged(object sender, EventArgs e)
        {
            TimeSpan timeShift = new TimeSpan();
            bool preview;
                if (comboBoxImages.SelectedIndex == -1) return;
                try
                {
                    //todo - using TryParse?
                    timeShift = DateTime.ParseExact(newDateTaken.Text, "yyyy:MM:dd HH:mm:ss", null) - DateTime.ParseExact(currentDateTaken.Text, "yyyy:MM:dd HH:mm:ss", null);
                    preview = true;
                }
                catch
                { preview = false; }

                string selectedFile = comboBoxImages.Items[comboBoxImages.SelectedIndex].ToString();
                string filePath = Path.Combine(textBoxSource.Text, selectedFile);
                Image photo;
                try
                {
                    photo = new Bitmap(filePath);
                    PropertyItem dateTimeShot = photo.GetPropertyItem(36867);
                    ASCIIEncoding encoding = new ASCIIEncoding();
                    string whenShot = encoding.GetString(dateTimeShot.Value);
                    whenShot = whenShot.Remove(19);
                    currentDateTaken.Text = whenShot;
                    if (preview)
                    {
                        DateTime tempDateTime = DateTime.ParseExact(whenShot, "yyyy:MM:dd HH:mm:ss", null);
                        tempDateTime += timeShift;
                        newDateTaken.Text = tempDateTime.ToString("yyyy:MM:dd HH:mm:ss");
                    }
                    else
                    {
                        newDateTaken.Text = whenShot;
                    }
                    pictureBoxSelected.ImageLocation = filePath;
                    pictureBoxSelected.SizeMode = PictureBoxSizeMode.Zoom;
                    photo.Dispose();
                }
                catch
                {
                    currentDateTaken.Text = "";
                    newDateTaken.Text = "";
                    pictureBoxSelected.ImageLocation = "";
                    MessageBox.Show("Could not read EXIF data from " + selectedFile);
                }
        }
开发者ID:grokkingly,项目名称:adjust-exif-time,代码行数:53,代码来源:Form1.cs


注:本文中的System.Drawing.Bitmap.GetPropertyItem方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。