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()); }
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; }
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; }
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); }
public void ImageFromResourceValid() { // Creates the ResourceManager. */ var rm = new System.Resources.ResourceManager("FindPhotosForMonthTests.Properties.Resources", this.GetType().Assembly); System.Drawing.Bitmap im = (System.Drawing.Bitmap)rm.GetObject("testImage01"); Assert.IsNotNull(im); Assert.AreEqual <Int32>(im.Width, 3024); Assert.AreEqual <Int32>(im.Height, 4032); Assert.AreEqual <Int32>(im.Flags, 73744); // retrieve propertyItems var val = im.GetPropertyItem(20624); Assert.AreEqual <byte>(val.Value[0], (byte)1); val = im.GetPropertyItem(20625); Assert.AreEqual <byte>(val.Value[0], (byte)1); }
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++; } */ }
/// <summary> /// /// </summary> /// <param name="file"></param> /// <returns></returns> private DateTime?GetTimeFoto(FileSystemInfo file) { DateTime?time; // Create an Image object. using (Image image = new System.Drawing.Bitmap(file.FullName)) { // Get the PropertyItems property from image. if (image.PropertyIdList.Length <= 0 || image.PropertyIdList.All(o => o != 0x132)) { return(null); } var property = image.GetPropertyItem(0x132); var text = new System.Text.ASCIIEncoding().GetString(property.Value, 0, property.Len - 1); time = DateTime.ParseExact(text, "yyyy:MM:d H:m:s", CultureInfo.InvariantCulture); } return(time); }
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); } }
/// <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 }); } }
private static Bitmap CorrectRotation(Bitmap bitmap) { if (Array.IndexOf (bitmap.PropertyIdList, 274) > -1) { var values = bitmap.GetPropertyItem (274).Value; //var dateTakenPropertyItem = bitmap.GetPropertyItem (0x9003); //var dateTakenString = Encoding.UTF8.GetString (dateTakenPropertyItem.Value); //var regex = new Regex (":"); //dateTakenString = dateTakenString.Substring (0, dateTakenString.Length - 1); //dateTakenString = regex.Replace (dateTakenString, "-", 2); //var dateTaken = DateTime.Parse (dateTakenString); if (values.Length < 1) return bitmap; var orientation = (int) values [0]; switch (orientation) { case 1: // No rotation required. break; case 2: bitmap.RotateFlip (RotateFlipType.RotateNoneFlipX); break; case 3: bitmap.RotateFlip (RotateFlipType.Rotate180FlipNone); break; case 4: bitmap.RotateFlip (RotateFlipType.Rotate180FlipX); break; case 5: bitmap.RotateFlip (RotateFlipType.Rotate90FlipX); break; case 6: bitmap.RotateFlip (RotateFlipType.Rotate90FlipNone); break; case 7: bitmap.RotateFlip (RotateFlipType.Rotate270FlipX); break; case 8: bitmap.RotateFlip (RotateFlipType.Rotate270FlipNone); break; } // This EXIF data is now invalid and should be removed. bitmap.RemovePropertyItem (274); } return bitmap; }
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"); address = element.InnerText; } string convert = CoordinatesConverter.CoordinatesConvertor(long_dd, lat_dd, 4326, 3414); string[] converting = convert.Split(','); x = Double.Parse(converting[0]); y = Double.Parse(converting[1]); } else { 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]); } } }
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; case 0x0213: SetMetadata("YCbCrPositioning", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x00FE: SetMetadata("NewSubfileType", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x00FF: SetMetadata("SubfileType", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0100: SetMetadata("ImageWidth", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x0101: SetMetadata("ImageHeight", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x0102: SetMetadata("BitsPerSample", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0103: SetMetadata("Compression", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0106: SetMetadata("PhotometricInterp", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0107: SetMetadata("ThreshHolding", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0108: SetMetadata("CellWidth", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0109: SetMetadata("CellHeight", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x010A: SetMetadata("FillOrder", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x010D: SetMetadata("DocumentName", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x010E: SetMetadata("ImageDescription", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x0111: SetMetadata("StripOffsets", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x0115: SetMetadata("SamplesPerPixel", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0116: SetMetadata("RowsPerStrip", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x0117: SetMetadata("StripBytesCount", ConvertByteArrayToLong(pi.Value).ToString(),imageMetaData); break; case 0x0118: SetMetadata("MinSampleValue", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0119: SetMetadata("MaxSampleValue", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x011C: SetMetadata("PlanarConfig", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x011D: SetMetadata("PageName", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x011E: SetMetadata("XPosition", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0x011F: SetMetadata("YPosition", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0x0120: SetMetadata("FreeOffset", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x0121: SetMetadata("FreeByteCounts", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x0122: SetMetadata("GrayResponseUnit", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0123: SetMetadata("GrayResponseCurve", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0124: SetMetadata("T4Option", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x0125: SetMetadata("T6Option", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x0129: SetMetadata("PageNumber", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x012D: SetMetadata("TransferFunction", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0131: SetMetadata("SoftwareUsed", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x013B: SetMetadata("Artist", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x013C: SetMetadata("HostComputer", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x013D: SetMetadata("Predictor", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x013E: SetMetadata("WhitePoint", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0x013F: SetMetadata("PrimaryChromaticities", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0x0140: SetMetadata("ColorMap", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0141: SetMetadata("HalftoneHints", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0142: SetMetadata("TileWidth", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x0143: SetMetadata("TileLength", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x0144: SetMetadata("TileOffset", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x0145: SetMetadata("TileByteCounts", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x014C: SetMetadata("InkSet", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x014D: SetMetadata("InkNames", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x014E: SetMetadata("NumberOfInks", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0150: SetMetadata("DotRange", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0151: SetMetadata("TargetPrinter", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x0152: SetMetadata("ExtraSamples", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0153: SetMetadata("SampleFormat", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0156: SetMetadata("TransferRange", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0200: SetMetadata("JPEGProc", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0201: SetMetadata("JPEGInterFormat", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x0202: SetMetadata("JPEGInterLength", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x0203: SetMetadata("JPEGRestartInterval", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0205: SetMetadata("JPEGLosslessPredictors", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0206: SetMetadata("JPEGPointTransforms", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0207: SetMetadata("JPEGQTables", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x0208: SetMetadata("JPEGDCTables", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x0209: SetMetadata("JPEGACTables", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x0211: SetMetadata("YCbCrCoefficients", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0x0212: SetMetadata("YCbCrSubsampling", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x0214: SetMetadata("REFBlackWhite", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0x0301: SetMetadata("Gamma", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0x0302: SetMetadata("ICCProfileDescriptor", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x0303: switch(ConvertByteArrayToShort(pi.Value)) { case 0: SetMetadata("SRGBRenderingIntent", "perceptual", imageMetaData); break; case 1: SetMetadata("SRGBRenderingIntent", "relative colorimetric", imageMetaData); break; case 2: SetMetadata("SRGBRenderingIntent", "saturation", imageMetaData); break; case 3: SetMetadata("SRGBRenderingIntent", "absolute colorimetric", imageMetaData); break; } break; case 0x0320: SetMetadata("ImageTitle", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x5001: SetMetadata("ResolutionXUnit", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x5002: SetMetadata("ResolutionYUnit", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x5003: SetMetadata("ResolutionXLengthUnit", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x5004: SetMetadata("ResolutionYLengthUnit", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x5005: SetMetadata("PrintFlags", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x5006: SetMetadata("PrintFlagsVersion", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x5007: SetMetadata("PrintFlagsCrop", ConvertByteArrayToByte(pi.Value).ToString(), imageMetaData); break; case 0x5008: SetMetadata("PrintFlagsBleedWidth", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x5009: SetMetadata("PrintFlagsBleedWidthScale", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x500A: SetMetadata("HalftoneLPI", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0x500B: SetMetadata("HalftoneLPIUnit", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x500C: SetMetadata("HalftoneDegree", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0x500D: SetMetadata("HalftoneShape", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x500E: SetMetadata("HalftoneMisc", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x500F: SetMetadata("HalftoneScreen", ConvertByteArrayToByte(pi.Value).ToString(), imageMetaData); break; case 0x5010: SetMetadata("JPEGQuality", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x5012: SetMetadata("ThumbnailFormat", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x5013: SetMetadata("ThumbnailWidth", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x5014: SetMetadata("ThumbnailHeight", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x5015: SetMetadata("ThumbnailColorDepth", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x5016: SetMetadata("ThumbnailPlanes", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x5017: SetMetadata("ThumbnailRawBytes", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x5018: SetMetadata("ThumbnailSize", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x5019: SetMetadata("ThumbnailCompressedSize", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x501B: SetMetadata("ThumbnailData", ConvertByteArrayToByte(pi.Value).ToString(), imageMetaData); break; case 0x5020: SetMetadata("ThumbnailImageWidth", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x5021: SetMetadata("ThumbnailImageHeight", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x5022: SetMetadata("ThumbnailBitsPerSample", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x5023: SetMetadata("ThumbnailCompression", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x5024: SetMetadata("ThumbnailPhotometricInterp", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x5025: SetMetadata("ThumbnailImageDescription", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x5026: SetMetadata("ThumbnailEquipMake", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x5027: SetMetadata("ThumbnailEquipModel", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x5028: SetMetadata("ThumbnailStripOffsets", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x5029: SetMetadata("ThumbnailOrientation", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x502A: SetMetadata("ThumbnailSamplesPerPixel", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x502B: SetMetadata("ThumbnailRowsPerStrip", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x502C: SetMetadata("ThumbnailStripBytesCount", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x502F: SetMetadata("ThumbnailPlanarConfig", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x5030: SetMetadata("ThumbnailResolutionUnit", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x5031: SetMetadata("ThumbnailTransferFunction", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x5032: SetMetadata("ThumbnailSoftwareUsed", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x5033: SetMetadata("ThumbnailDateTime", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x5034: SetMetadata("ThumbnailArtist", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x5035: SetMetadata("ThumbnailWhitePoint", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0x5036: SetMetadata("ThumbnailPrimaryChromaticities", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0x5037: SetMetadata("ThumbnailYCbCrCoefficients", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0x5038: SetMetadata("ThumbnailYCbCrSubsampling", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x5039: SetMetadata("ThumbnailYCbCrPositioning", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x503A: SetMetadata("ThumbnailRefBlackWhite", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0x503B: SetMetadata("ThumbnailCopyRight", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x5090: SetMetadata("LuminanceTable", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x5091: SetMetadata("ChrominanceTable", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x5100: SetMetadata("FrameDelay", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x5101: SetMetadata("LoopCount", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x5110: SetMetadata("PixelUnit", ConvertByteArrayToByte(pi.Value).ToString(), imageMetaData); break; case 0x5111: SetMetadata("PixelPerUnitX", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x5112: SetMetadata("PixelPerUnitY", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x5113: SetMetadata("PaletteHistogram", ConvertByteArrayToByte(pi.Value).ToString(), imageMetaData); break; case 0x8298: SetMetadata("Copyright", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x829A: SetMetadata("ExifExposureTime", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0x829D: SetMetadata("ExifFNumber", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0x8769: SetMetadata("ExifIFD", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x8773: SetMetadata("ICCProfile", ConvertByteArrayToByte(pi.Value).ToString(), imageMetaData); break; case 0x8822: switch(ConvertByteArrayToShort(pi.Value)) { case 0: SetMetadata("ExifExposureProg", "Not defined", imageMetaData); break; case 1: SetMetadata("ExifExposureProg", "Manual", imageMetaData); break; case 2: SetMetadata("ExifExposureProg", "Normal Program", imageMetaData); break; case 3: SetMetadata("ExifExposureProg", "Aperture Priority", imageMetaData); break; case 4: SetMetadata("ExifExposureProg", "Shutter Priority", imageMetaData); break; case 5: SetMetadata("ExifExposureProg", "Creative program (biased toward depth of field)", imageMetaData); break; case 6: SetMetadata("ExifExposureProg", "Action program (biased toward fast shutter speed)", imageMetaData); break; case 7: SetMetadata("ExifExposureProg", "Portrait mode (for close-up photos with the background out of focus)", imageMetaData); break; case 8: SetMetadata("ExifExposureProg", "Landscape mode (for landscape photos with the background in focus)", imageMetaData); break; default: SetMetadata("ExifExposureProg", "Unknown", imageMetaData); break; } break; case 0x8824: SetMetadata("ExifSpectralSense", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x8825: SetMetadata("GpsIFD", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0x8827: SetMetadata("ExifISOSpeed", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0x9003: SetMetadata("ExifDTOrig", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x9004: SetMetadata("ExifDTDigitized", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x9102: SetMetadata("ExifCompBPP", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0x9201: SetMetadata("ExifShutterSpeed", ConvertByteArrayToSRational(pi.Value), imageMetaData); break; case 0x9202: SetMetadata("ExifAperture", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0x9203: SetMetadata("ExifBrightness", ConvertByteArrayToSRational(pi.Value), imageMetaData); break; case 0x9204: SetMetadata("ExifExposureBias", ConvertByteArrayToSRational(pi.Value), imageMetaData); break; case 0x9205: SetMetadata("ExifMaxAperture", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0x9206: SetMetadata("ExifSubjectDist", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0x9207: switch(ConvertByteArrayToShort(pi.Value)) { case 0: SetMetadata("ExifMeteringMode", "Unknown", imageMetaData); break; case 1: SetMetadata("ExifMeteringMode", "Average", imageMetaData); break; case 2: SetMetadata("ExifMeteringMode", "CenterWeightedAverage", imageMetaData); break; case 3: SetMetadata("ExifMeteringMode", "Spot", imageMetaData); break; case 4: SetMetadata("ExifMeteringMode", "MultiSpot", imageMetaData); break; case 5: SetMetadata("ExifMeteringMode", "Pattern", imageMetaData); break; case 6: SetMetadata("ExifMeteringMode", "Partial", imageMetaData); break; case 255: SetMetadata("ExifMeteringMode", "Other", imageMetaData); break; default: SetMetadata("ExifMeteringMode", "Unknown", imageMetaData); break; } break; case 0x9208: switch(ConvertByteArrayToShort(pi.Value)) { case 0: SetMetadata("ExifLightSource", "Unknown", imageMetaData); break; case 1: SetMetadata("ExifLightSource", "Daylight", imageMetaData); break; case 2: SetMetadata("ExifLightSource", "Flourescent", imageMetaData); break; case 3: SetMetadata("ExifLightSource", "Tungsten", imageMetaData); break; case 17: SetMetadata("ExifLightSource", "Standard Light A", imageMetaData); break; case 18: SetMetadata("ExifLightSource", "Standard Light B", imageMetaData); break; case 19: SetMetadata("ExifLightSource", "Standard Light C", imageMetaData); break; case 20: SetMetadata("ExifLightSource", "D55", imageMetaData); break; case 21: SetMetadata("ExifLightSource", "D65", imageMetaData); break; case 22: SetMetadata("ExifLightSource", "D75", imageMetaData); break; case 255: SetMetadata("ExifLightSource", "Other", imageMetaData); break; default: SetMetadata("ExifLightSource", "Unknown", imageMetaData); break; } break; case 0x9209: switch(ConvertByteArrayToShort(pi.Value)) { case 0: SetMetadata("ExifFlash", "Flash did not fire", imageMetaData); break; case 1: SetMetadata("ExifFlash", "Flash fired", imageMetaData); break; case 5: SetMetadata("ExifFlash", "Strobe return light not detected", imageMetaData); break; default: SetMetadata("ExifFlash", "Uknown", imageMetaData); break; } break; case 0x920A: SetMetadata("ExifFocalLength", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0x9290: SetMetadata("ExifDTSubsec", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x9291: SetMetadata("ExifDTOrigSS", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0x9292: SetMetadata("ExifDTDigSS", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0xA001: switch(ConvertByteArrayToLong(pi.Value)) { case 0x1: SetMetadata("ExifColorSpace", "sRGB", imageMetaData); break; case 0xFFFF: SetMetadata("ExifColorSpace", "Uncalibrated", imageMetaData); break; default: SetMetadata("ExifColorSpace", "Reserved", imageMetaData); break; } break; case 0xA002: SetMetadata("ExifPixXDim", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0xA003: SetMetadata("ExifPixYDim", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0xA004: SetMetadata("ExifRelatedWav", ConvertByteArrayToString(pi.Value), imageMetaData); break; case 0xA005: SetMetadata("ExifInterop", ConvertByteArrayToLong(pi.Value).ToString(), imageMetaData); break; case 0xA20B: SetMetadata("ExifFlashEnergy", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0xA20E: SetMetadata("ExifFocalXRes", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0xA20F: SetMetadata("ExifFocalYRes", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0xA210: switch(ConvertByteArrayToShort(pi.Value)) { case 2: SetMetadata("ExifFocalResUnit", "Inch", imageMetaData); break; case 3: SetMetadata("ExifFocalResUnit", "Centimeter", imageMetaData); break; } break; case 0xA214: SetMetadata("ExifSubjectLoc", ConvertByteArrayToShort(pi.Value).ToString(), imageMetaData); break; case 0xA215: SetMetadata("ExifExposureIndex", ConvertByteArrayToRational(pi.Value), imageMetaData); break; case 0xA217: switch(ConvertByteArrayToShort(pi.Value)) { case 1: SetMetadata("ExifSensingMethod", "Not defined", imageMetaData); break; case 2: SetMetadata("ExifSensingMethod", "One-chip color area sensor", imageMetaData); break; case 3: SetMetadata("ExifSensingMethod", "Two-chip color area sensor", imageMetaData); break; case 4: SetMetadata("ExifSensingMethod", "Three-chip color area sensor", imageMetaData); break; case 5: SetMetadata("ExifSensingMethod", "Color sequential area sensor", imageMetaData); break; case 7: SetMetadata("ExifSensingMethod", "Trilinear sensor", imageMetaData); break; case 8: SetMetadata("ExifSensingMethod", "Color sequential linear sensor", imageMetaData); break; default: SetMetadata("ExifSensingMethod", "Reserved", imageMetaData); break; } break; } } } }
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; })); }
/// <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(); } }
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; } }
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); })); } }
/// <summary> /// Ładuje teksturę. /// Jeśli nie może załadować używa domyślnej tekstury. /// </summary> /// <returns>Stan załadowania zasobu.</returns> public virtual Interfaces.ResourceLoadingState Load() { lock (this.PadLock) { try { this.UserData = string.Empty; GL.Enable(EnableCap.Texture2D); using (Bitmap bm = new Bitmap(this.FileName)) { BitmapData data = bm.LockBits(new Rectangle(0, 0, bm.Width, bm.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); this.Size = new Vector2(bm.Width, bm.Height); this.TextureId = GL.GenTexture(); this.Bind(); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bm.Width, bm.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0); bm.UnlockBits(data); //Pobieramy dane z właściwości PropertyItem property = null; foreach (var propId in Properties) { try { property = bm.GetPropertyItem(propId); //PropertyTagImageTitle break; } catch { } } Match match; if((property != null && (match = UserDataRegex.Match(Encoding.Default.GetString(property.Value))).Success) || (match = UserDataRegex.Match(this.Id)).Success) { this.UserData = match.Groups[1].Value; } } //Ustawiamy filtrowanie - w grach 2D linearne nas zadowala. GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); } catch (Exception ex) { Logger.WarnException("Cannot load texture. Using default.", ex); DefaultTexture.Instance.Load(); this.DefaultUsed = true; this.TextureId = DefaultTexture.Instance.TextureId; this.Size = DefaultTexture.Instance.Size; return Interfaces.ResourceLoadingState.DefaultUsed; } return Interfaces.ResourceLoadingState.Success; } }
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(); } } int categoryId = sourceGallery.MaxId; foreach (var category in gallery.Categories) { categoryId++; category.Id = categoryId; } if (gallery.Categories != null && gallery.Categories.Count > 0) { sourceGallery.Categories.AddRange(gallery.Categories); } sourceGallery.Categories.Sort(); int pageId = 0; foreach (var category in sourceGallery.Categories) { pageId++; category.Page = pageId; } try { StorageHelper.SaveGallery(sourceGallery); } catch (Exception ex) { MessageBox.Show("SaveGallery Error:" + ex.Message); } MessageBox.Show(string.Format("Done!\n共转换{0}个文件,耗时{1}秒", doneFilesCount, (DateTime.Now - startTime).TotalSeconds), "成功", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show("Build Error:" + ex.Message); } }
public static Bitmap WaterMarkWithText(System.Drawing.Bitmap origialGif, string text, string filePath) { //用于存放桢 List <Frame> frames = new List <Frame>(); //如果不是gif文件,直接返回原图像 if (origialGif.RawFormat.Guid != System.Drawing.Imaging.ImageFormat.Gif.Guid) { return(origialGif); } //如果该图像是gif文件 foreach (Guid guid in origialGif.FrameDimensionsList) { System.Drawing.Imaging.FrameDimension frameDimension = new System.Drawing.Imaging.FrameDimension(guid); int frameCount = origialGif.GetFrameCount(frameDimension); for (int i = 0; i < frameCount; i++) { if (origialGif.SelectActiveFrame(frameDimension, i) == 0) { int delay = Convert.ToInt32(origialGif.GetPropertyItem(20736).Value.GetValue(i)); Image img = Image.FromHbitmap(origialGif.GetHbitmap()); Font font = new Font(new FontFamily("宋体"), 35.0f, FontStyle.Bold); Graphics g = Graphics.FromImage(img); g.DrawString(text, font, Brushes.BlanchedAlmond, new PointF(10.0f, 10.0f)); Frame frame = new Frame(img, delay); frames.Add(frame); } } //Gif.Components.AnimatedGifEncoder gif = //new Gif.Components.AnimatedGifEncoder(); //gif.Start(filePath); //gif.SetDelay(100); //gif.SetRepeat(0); //for (int i = 0; i < //frames.Count; i++) //{ // gif.AddFrame(frames[i].Image); //} //gif.Finish(); try { Bitmap gifImg = (Bitmap)Bitmap.FromFile(filePath); return(gifImg); } catch { return(origialGif); } } return(origialGif); }
//===================================================================== FUNCTIONS public void LoadImage(Bitmap image) { DisposeImage(); try { _currentImage = image; _frameDimension = new FrameDimension(_currentImage.FrameDimensionsList[0]); if (FrameCount > 1) { _timerGIF.Interval = BitConverter.ToInt32(_currentImage.GetPropertyItem(0x5100).Value, 0) * 10; _timerGIF.Enabled = true; } else _timerGIF.Enabled = false; FitToScreen(); this.Invalidate(); } catch (Exception ex) { throw ex; } }
/// <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); } }
/// <summary> /// The worker function for patch processing. This is to be started as a separate thread. /// </summary> private void processPhotos() { Random r = new Random((int)DateTime.Now.Ticks); List<string> files = new List<string>(); files.AddRange(Directory.GetFiles(path, "*.jpg")); files.AddRange(Directory.GetFiles(path, "*.jpeg")); this.BeginInvoke((Action)(() => progressBar1.Value = 0)); this.BeginInvoke((Action)(() => progressBar1.Step = 1)); this.BeginInvoke((Action)(() => progressBar1.Maximum = files.Count + 1)); this.BeginInvoke((Action)(() => progressBar1.PerformStep())); // do one progress bar step immediately to indicate we have started processing foreach (string file in files) { exifDateString = combinedTime.ToString("yyyy:MM:dd HH:mm:ss"); // set EXIF data to specified time // http://www.media.mit.edu/pia/Research/deepview/exif.html //0x0132 DateTime ascii string 20 Date/Time of image was last modified. Data format is "YYYY:MM:DD HH:MM:SS"+0x00, total 20bytes. In usual, it has the same value of DateTimeOriginal(0x9003) //0x9003 DateTimeOriginal ascii string 20 Date/Time of original image taken. This value should not be modified by user program. //0x9004 DateTimeDigitized ascii string 20 Date/Time of image digitized. Usually, it contains the same value of DateTimeOriginal(0x9003). // http://archive.msdn.microsoft.com/changexifwithcsharp Image iOrig = new Bitmap(file); ImageFormat ifOrig = iOrig.RawFormat; PropertyItem exifDateTimeProp = iOrig.GetPropertyItem(EXIF_DATE_TIME); PropertyItem exifDateTimeOrigProp = iOrig.GetPropertyItem(EXIF_DATE_TIME_ORIGINAL); PropertyItem exifDateTimeDigiProp = iOrig.GetPropertyItem(EXIF_DATE_TIME_DIGITIZED); exifDateTimeProp.Value = System.Text.Encoding.UTF8.GetBytes(exifDateString); exifDateTimeOrigProp.Value = System.Text.Encoding.UTF8.GetBytes(exifDateString); exifDateTimeDigiProp.Value = System.Text.Encoding.UTF8.GetBytes(exifDateString); iOrig.SetPropertyItem(exifDateTimeProp); iOrig.SetPropertyItem(exifDateTimeOrigProp); iOrig.SetPropertyItem(exifDateTimeDigiProp); Image iSave = new Bitmap(iOrig.Width, iOrig.Height, iOrig.PixelFormat); Graphics gSave = Graphics.FromImage(iSave); gSave.DrawImage(iOrig, 0, 0, iOrig.Width, iOrig.Height); foreach (PropertyItem i in iOrig.PropertyItems) iSave.SetPropertyItem(i); // WHAT THE F**K?! // You *HAVE* to dispose these two objects, iOrig and gSave, BEFORE you save iSave otherwise // you'll get an unexplained GDI+ exception... THANK YOU MICROSOFT! >:( iOrig.Dispose(); gSave.Dispose(); iSave.Save(file, ifOrig); iSave.Dispose(); // set file create, mod, and access time to the specified time // (this has to be done after the EXIF modification because that will modify the file, of course) File.SetCreationTime(file, combinedTime); File.SetLastWriteTime(file, combinedTime); File.SetLastAccessTime(file, combinedTime); if (chkRandomize.Checked) { // randomize the time to between 0800 and 1600 to make it believable: int hour = r.Next(8, 17); int minute = r.Next(60); int second = r.Next(60); int millisecond = r.Next(1000); combinedTime = new DateTime(combinedTime.Year, combinedTime.Month, combinedTime.Day, hour, minute, second, millisecond); } // do progressbar step after we finished a file to give accurate feedback this.BeginInvoke((Action)(() => progressBar1.PerformStep())); } MessageBox.Show("Finished Processing.", "Success"); this.BeginInvoke((Action)(() => progressBar1.Value = 0)); }
/// <summary> /// イメージのExif情報付きJpegファイル保存(PSPビデオ用サムネイル /// 画像用ファイルのため160x120固定) /// </summary> /// <param name="path">保存するファイル名</param> /// <param name="bmp">保存するイメージ</param> public void exifImageSave(Image bmp, string path) { string date = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); //"2009:01:01 00:00:00"; // Exif情報を0から作成できないため(コンストラクタがない)、 // リソースにあるExif情報付きJPEGファイルを開いて取得したExif情報を使用する Image exif = new Bitmap(this.GetType(), "exif.jpg"); PropertyItem pi = exif.GetPropertyItem(0x9003); pi.Value = Encoding.ASCII.GetBytes(date + '\0'); pi.Len = pi.Value.Length; // アスペクト比保持のための処理 int imageX = bmp.Width; int imageY = bmp.Height; int thmX = 0; int thmY = 0; int newX = 0; int newY = 0; const double thmImageWidth = 160.0; const double thmImageHeight = 120.0; double dwImageWidth = Convert.ToDouble(imageX); double dwImageHeight = Convert.ToDouble(imageY); // 大きい方を固定値にする if (imageX > imageY) { thmX = 160; thmY = Convert.ToInt32(thmImageWidth / dwImageWidth * dwImageHeight); newX = 0; newY = Convert.ToInt32((thmImageHeight - Convert.ToDouble(thmY)) / 2.0); } else { thmX = Convert.ToInt32(thmImageHeight / dwImageHeight * dwImageWidth); thmY = 120; newX = Convert.ToInt32((thmImageWidth - Convert.ToDouble(thmX)) / 2.0); newY = 0; } // サムネイル画像作成 Image img = bmp.GetThumbnailImage(thmX, thmY, null, IntPtr.Zero); // THM用固定サイズの画像作成 Bitmap bmp2 = new Bitmap(160, 120); Graphics grp = Graphics.FromImage(bmp2); // 160x120の画像に、160 x nn or mm x 120のサムネイル画像を上書きコピー grp.DrawImage(img, newX, newY, thmX, thmY); img = bmp2; // Exif情報を付加してJPEGファイルとして保存 img.SetPropertyItem(pi); img.Save(path, ImageFormat.Jpeg); img.Dispose(); }