/// <summary> /// /// </summary> /// <param name="image"></param> /// <param name="id"></param> public static void Change(System.Drawing.Image image, int id, byte[] value) { if (image is System.Drawing.Image && ExifFormat.Contains(image.RawFormat)) { var pi = image.GetPropertyItem(id); pi.Value = value; image.SetPropertyItem(pi); } }
private void Normalize() { bool rotated = false; try { var property = image.GetPropertyItem(OrientationPropertyId); var rotateFlip = GetCurrentImageOrientation(GetPropertyValue(property)).GetNormalizationRotation(); property.Value = BitConverter.GetBytes((short)1); image.SetPropertyItem(property); if (rotateFlip != RotateFlipType.RotateNoneFlipNone) { rotated = true; image.RotateFlip(rotateFlip); } } catch (Exception) { // Possible image does not have EXIF properties. May simple rotation } if (image.Width > image.Height) { image.RotateFlip(rotated ? RotateFlipType.Rotate270FlipNone : RotateFlipType.Rotate90FlipNone); } }
//------------------------------------------------------------------------------- // public ImageAnimation(Image img) { _image = img; FrameDimension = new FrameDimension(img.FrameDimensionsList[0]); MaxFrameCount = img.GetFrameCount(FrameDimension); PropertyItem pItemFrameDelay = img.GetPropertyItem(FRAME_DELAY); PropertyItem pItemFrameNum = img.GetPropertyItem(FRAME_NUM); FrameDelays = new int[MaxFrameCount]; for (int i = 0; i < MaxFrameCount; i++) { FrameDelays[i] = BitConverter.ToInt32(pItemFrameDelay.Value, 4 * i); } MaxLoopCount = BitConverter.ToInt16(pItemFrameNum.Value, 0); LoopInfinity = (MaxLoopCount == 0); _timer = new Timer(Timer_Elapsed, null, Timeout.Infinite, Timeout.Infinite); try { _image.SelectActiveFrame(FrameDimension, 0); } catch (InvalidOperationException/* ex*/) { //Log.DebugLog(ex); //Debug.Assert(false, "Image.SelectActiveFrame失敗"); } }
public static Gif ImageToGif(Image i) { FrameDimension dimension = new FrameDimension(i.FrameDimensionsList[0]); int[] timings = new int[i.GetFrameCount(dimension)]; return(new Gif(Enumerable.Range(0, i.GetFrameCount(dimension)). Select(x => { i.SelectActiveFrame(dimension, x); try { timings[x] = BitConverter.ToInt32(i.GetPropertyItem(20736).Value, x * 4) * 10; // this works on windows sometimes } catch { try { var prop = i.GetPropertyItem(20736); timings[x] = (prop.Value[0] + prop.Value[1] * 256) * 10; // this works according to https://stackoverflow.com/questions/3785031/getting-the-frame-duration-of-an-animated-gif } catch { timings[x] = 33; // just set it to 30fps lul, works for consoles } } return new Bitmap(i); }). ToArray(), timings)); }
public ImageInfo(Image image) { _image = image; _animated = ImageAnimator.CanAnimate(image); _frameEndTimes = null; if (_animated) { _frameCount = image.GetFrameCount(FrameDimension.Time); PropertyItem?frameDelayItem = image.GetPropertyItem(PropertyTagFrameDelay); // If the image does not have a frame delay, we just return 0. if (frameDelayItem != null) { // Convert the frame delay from byte[] to int byte[] values = frameDelayItem.Value !; // On Windows, we get the frame delays for every frame. On Linux, we only get the first frame delay. // We handle this by treating the frame delays as a repeating sequence, asserting that the sequence // is fully repeatable to match the frame count. Debug.Assert(values.Length % 4 == 0, "PropertyItem has an invalid value byte array. It should have a length evenly divisible by 4 to represent ints."); Debug.Assert(_frameCount % (values.Length / 4) == 0, "PropertyItem has invalid value byte array. The FrameCount should be evenly divisible by a quarter of the byte array's length."); _frameEndTimes = new long[_frameCount]; long lastEndTime = 0; for (int f = 0, i = 0; f < _frameCount; ++f, i += 4) { if (i >= values.Length) { i = 0; } // Frame delays are stored in 1/100ths of a second; convert to milliseconds while accumulating _frameEndTimes[f] = (lastEndTime += (BitConverter.ToInt32(values, i) * 10)); } } PropertyItem?loopCountItem = image.GetPropertyItem(PropertyTagLoopCount); if (loopCountItem != null) { // The loop count is a short where 0 = infinite, and a positive value indicates the // number of times to loop. The animation will be shown 1 time more than the loop count. byte[] values = loopCountItem.Value !; Debug.Assert(values.Length == sizeof(short), "PropertyItem has an invalid byte array. It should represent a single short value."); _loopCount = BitConverter.ToInt16(values); } else { _loopCount = 0; } } else { _frameCount = 1; } }
/// <summary> /// Initializes a new instance of the <see cref="GifDecoder"/> class. /// </summary> /// <param name="image"> /// The <see cref="Image"/> to decode. /// </param> public GifDecoder(Image image) { this.Height = image.Height; this.Width = image.Width; if (FormatUtilities.IsAnimated(image)) { this.IsAnimated = true; if (this.IsAnimated) { int frameCount = image.GetFrameCount(FrameDimension.Time); int last = frameCount - 1; double length = 0; List<GifFrame> gifFrames = new List<GifFrame>(); // Get the times stored in the gif. byte[] times = image.GetPropertyItem((int)ExifPropertyTag.FrameDelay).Value; for (int i = 0; i < frameCount; i++) { // Convert each 4-byte chunk into an integer. // GDI returns a single array with all delays, while Mono returns a different array for each frame. TimeSpan delay = TimeSpan.FromMilliseconds(BitConverter.ToInt32(times, (4 * i) % times.Length) * 10); // Find the frame image.SelectActiveFrame(FrameDimension.Time, i); Bitmap frame = new Bitmap(image); frame.SetResolution(image.HorizontalResolution, image.VerticalResolution); // TODO: Get positions. gifFrames.Add(new GifFrame { Delay = delay, Image = frame }); // Reset the position. if (i == last) { image.SelectActiveFrame(FrameDimension.Time, 0); } length += delay.TotalMilliseconds; } this.GifFrames = gifFrames; this.AnimationLength = length; // Loop info is stored at byte 20737. this.LoopCount = BitConverter.ToInt16(image.GetPropertyItem((int)ExifPropertyTag.LoopCount).Value, 0); this.IsLooped = this.LoopCount != 1; } } }
public static float? GetLatitude(Image targetImg) { try { //Property Item 0x0001 - PropertyTagGpsLatitudeRef PropertyItem propItemRef = targetImg.GetPropertyItem(1); //Property Item 0x0002 - PropertyTagGpsLatitude PropertyItem propItemLat = targetImg.GetPropertyItem(2); return ExifGpsToFloat(propItemRef, propItemLat); } catch (ArgumentException) { return null; } }
public static float? GetLongitude(Image targetImg) { try { ///Property Item 0x0003 - PropertyTagGpsLongitudeRef PropertyItem propItemRef = targetImg.GetPropertyItem(3); //Property Item 0x0004 - PropertyTagGpsLongitude PropertyItem propItemLong = targetImg.GetPropertyItem(4); return ExifGpsToFloat(propItemRef, propItemLong); } catch (ArgumentException) { return null; } }
/// <summary> /// Rotates the image when posted from mobile (mobile pictures were showing up sideways on computers) /// </summary> /// <param name="image">The image model containing the image file from HttpPostedFiledBase class</param> /// <returns>The properly rotated image as a System.Drawing.Image</returns> public System.Drawing.Image ImageRotation(Models.Image image) { System.Drawing.Image originalImage = System.Drawing.Image.FromStream(image.ImageFile.InputStream, true, true); if (originalImage.PropertyIdList.Contains(0x0112)) { int rotationValue = originalImage.GetPropertyItem(0x0112).Value[0]; switch (rotationValue) { case 1: // landscape, do nothing break; case 8: // rotated 90 right // de-rotate: originalImage.RotateFlip(rotateFlipType: RotateFlipType.Rotate270FlipNone); break; case 3: // bottoms up originalImage.RotateFlip(rotateFlipType: RotateFlipType.Rotate180FlipNone); break; case 6: // rotated 90 left originalImage.RotateFlip(rotateFlipType: RotateFlipType.Rotate90FlipNone); break; } } return(originalImage); }
public void focal_Length(string path) { try { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) using (System.Drawing.Image myImage = System.Drawing.Image.FromStream(fs, false, false)) { PropertyItem propItem = myImage.GetPropertyItem(37386); //type 5 Fraction[] _resFraction = new Fraction[propItem.Len / (64 / 8)]; uint uNominator; uint uDenominator; for (int i = 0; i < _resFraction.Length; i++) { uNominator = BitConverter.ToUInt32(propItem.Value, i * (64 / 8)); uDenominator = BitConverter.ToUInt32(propItem.Value, i * (64 / 8) + (32 / 8)); _resFraction[i] = new Fraction(uNominator, uDenominator); } if (_resFraction.Length == 1) lblfocal_Length.Text = _resFraction[0].ToString() + "mm"; else lblfocal_Length.Text = "null"; } } catch { lblfocal_Length.Text = "Null"; } }
//retrieves the datetime WITHOUT loading the whole image public static DateTime GetDateTakenFromImage(string path) { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { using (System.Drawing.Image myImage = System.Drawing.Image.FromStream(fs, false, false)) { System.Drawing.Imaging.PropertyItem?propItem = null; try { propItem = myImage.GetPropertyItem(36867); } catch { } if (propItem != null) { string r = System.Text.Encoding.UTF8.GetString(propItem.Value); string dateTaken = r.Replace(":", ""); return(DateTime.Parse(dateTaken)); } else { return(new FileInfo(path).LastWriteTime); } } } }
public static void ImageResize(string inputPath, string fileName, string outFileName, int size, int quality) { try { using (System.Drawing.Image img = System.Drawing.Image.FromFile(Path.Combine(inputPath, fileName))) { foreach (var prop in img.PropertyItems) { if (prop.Id == 0x0112) //value of EXIF { int orientationValue = img.GetPropertyItem(prop.Id).Value[0]; RotateFlipType rotateFlipType = GetOrientationToFlipType(orientationValue); img.RotateFlip(rotateFlipType); break; } } using (var image = new Bitmap(img)) { int width, height; if (image.Width > image.Height) { width = size; height = Convert.ToInt32(image.Height * size / (double)image.Width); } else { width = Convert.ToInt32(image.Width * size / (double)image.Height); height = size; } var resized = new Bitmap(width, height); using (var graphics = Graphics.FromImage(resized)) { graphics.CompositingQuality = CompositingQuality.HighSpeed; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.CompositingMode = CompositingMode.SourceCopy; graphics.DrawImage(image, 0, 0, width, height); using (var output = File.Open(Path.Combine(inputPath, outFileName), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) { var qualityParamId = Encoder.Quality; var encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(qualityParamId, quality); var codec = ImageCodecInfo.GetImageDecoders().FirstOrDefault(im => im.FormatID == ImageFormat.Png.Guid); resized.Save(output, codec, encoderParameters); output.Close(); output.Dispose(); graphics.Dispose(); resized.Dispose(); } } image.Dispose(); } img.Dispose(); } } catch { throw; } //return inputPath; }
//auto rotate and save image private void SaveImage(FileUpload fileUpload) { byte[] imageData = new byte[fileUpload.PostedFile.ContentLength]; fileUpload.PostedFile.InputStream.Read(imageData, 0, fileUpload.PostedFile.ContentLength); MemoryStream ms = new MemoryStream(imageData); System.Drawing.Image originalImage = System.Drawing.Image.FromStream(ms); if (originalImage.PropertyIdList.Contains(0x0112)) { int rotationValue = originalImage.GetPropertyItem(0x0112).Value[0]; switch (rotationValue) { case 1: // landscape, do nothing break; case 8: // rotated 90 right // de-rotate: originalImage.RotateFlip(rotateFlipType: RotateFlipType.Rotate270FlipNone); break; case 3: // bottoms up originalImage.RotateFlip(rotateFlipType: RotateFlipType.Rotate180FlipNone); break; case 6: // rotated 90 left originalImage.RotateFlip(rotateFlipType: RotateFlipType.Rotate90FlipNone); break; } } originalImage.Save(Server.MapPath("~/Data/") + fileUpload.FileName); }
public void shutter_Speed(string path) { try { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) using (System.Drawing.Image myImage = System.Drawing.Image.FromStream(fs, false, false)) { PropertyItem propItem = myImage.GetPropertyItem(33434); Fraction[] _resFraction = new Fraction[propItem.Len / (64 / 8)]; int sNominator; int sDenominator; for (int i = 0; i < _resFraction.Length; i++) { sNominator = BitConverter.ToInt32(propItem.Value, i * (64 / 8)); sDenominator = BitConverter.ToInt32(propItem.Value, i * (64 / 8) + (32 / 8)); _resFraction[i] = new Fraction(sNominator, sDenominator); } if (_resFraction.Length == 1) lblshutter_Speed.Text = _resFraction[0].ToString(); else lblshutter_Speed.Text = "null"; } } catch { lblshutter_Speed.Text = "Null"; } }
public ImageInfo(Image image) { _image = image; _animated = ImageAnimator.CanAnimate(image); if (_animated) { _frameCount = image.GetFrameCount(FrameDimension.Time); PropertyItem frameDelayItem = image.GetPropertyItem(PropertyTagFrameDelay); // If the image does not have a frame delay, we just return 0. // if (frameDelayItem != null) { // Convert the frame delay from byte[] to int // byte[] values = frameDelayItem.Value; Debug.Assert(values.Length == 4 * FrameCount, "PropertyItem has invalid value byte array"); _frameDelay = new int[FrameCount]; for (int i = 0; i < FrameCount; ++i) { _frameDelay[i] = values[i * 4] + 256 * values[i * 4 + 1] + 256 * 256 * values[i * 4 + 2] + 256 * 256 * 256 * values[i * 4 + 3]; } } } else { _frameCount = 1; } if (_frameDelay == null) { _frameDelay = new int[FrameCount]; } }
/// <devdoc> /// </devdoc> public ImageInfo(Image image) { this.image = image; animated = ImageAnimator.CanAnimate(image); if (animated) { frameCount = image.GetFrameCount(FrameDimension.Time); PropertyItem frameDelayItem = image.GetPropertyItem(PropertyTagFrameDelay); // If the image does not have a frame delay, we just return 0. // if (frameDelayItem != null) { // Convert the frame delay from byte[] to int // byte[] values = frameDelayItem.Value; Debug.Assert(values.Length == 4 * FrameCount, "PropertyItem has invalid value byte array"); frameDelay = new int[FrameCount]; for (int i=0; i < FrameCount; ++i) { frameDelay[i] = values[i * 4] + 256 * values[i * 4 + 1] + 256 * 256 * values[i * 4 + 2] + 256 * 256 * 256 * values[i * 4 + 3]; } } } else { frameCount = 1; } if (frameDelay == null) { frameDelay = new int[FrameCount]; } }
public void iso_Speed(string path) { try { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) using (System.Drawing.Image myImage = System.Drawing.Image.FromStream(fs, false, false)) { PropertyItem propItem = myImage.GetPropertyItem(34855); //type 5 ushort[] _resUshort = new ushort[propItem.Len / (16 / 8)]; for (int i = 0; i < _resUshort.Length; i++) { _resUshort[i] = BitConverter.ToUInt16(propItem.Value, i * (16 / 8)); } if (_resUshort.Length == 1) { isoSpeed = _resUshort[0].ToString(); lbliso_Speed.Text = isoSpeed; } else { lbliso_Speed.Text = "- No Value"; isoSpeed = "- No Value"; } } } catch { lbliso_Speed.Text = "- No Value"; isoSpeed = "- No Value"; } }
public static void Animate (Image image, EventHandler onFrameChangedHandler) { // must be non-null and contain animation time frames if (!CanAnimate (image)) return; // is animation already in progress ? if (ht.ContainsKey (image)) return; PropertyItem item = image.GetPropertyItem (0x5100); // FrameDelay in libgdiplus byte[] value = item.Value; int[] delay = new int [(value.Length >> 2)]; for (int i=0, n=0; i < value.Length; i += 4, n++) { int d = BitConverter.ToInt32 (value, i) * 10; // follow worse case (Opera) see http://news.deviantart.com/article/27613/ delay [n] = d < 100 ? 100 : d; } AnimateEventArgs aea = new AnimateEventArgs (image); WorkerThread wt = new WorkerThread (onFrameChangedHandler, aea, delay); Thread thread = new Thread (new ThreadStart (wt.LoopHandler)); thread.IsBackground = true; aea.RunThread = thread; ht.Add (image, aea); thread.Start (); }
public static void Animate(Image image, EventHandler onFrameChangedHandler) { // must be non-null and contain animation time frames if (!CanAnimate(image)) { return; } // is animation already in progress ? if (ht.ContainsKey(image)) { return; } PropertyItem item = image.GetPropertyItem(0x5100); // FrameDelay in libgdiplus byte[] value = item.Value !; int[] delay = new int[(value.Length >> 2)]; for (int i = 0, n = 0; i < value.Length; i += 4, n++) { int d = BitConverter.ToInt32(value, i) * 10; // follow worse case (Opera) see http://news.deviantart.com/article/27613/ delay[n] = d < 100 ? 100 : d; } AnimateEventArgs aea = new AnimateEventArgs(image); WorkerThread wt = new WorkerThread(onFrameChangedHandler, aea, delay); Thread thread = new Thread(new ThreadStart(wt.LoopHandler)); thread.IsBackground = true; aea.RunThread = thread; ht.Add(image, aea); thread.Start(); }
/// <summary> /// Gets the <see cref="PropertyItem" /> specified by the <see cref="PropertyTag" />. /// </summary> /// <param name="image">The image to get the <see cref="PropertyItem" /> from.</param> /// <param name="property">The requested property.</param> /// <returns>The requested <see cref="PropertyItem" /> on success</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="image" /> is <see langword="null" />.</exception> /// <exception cref="ArgumentException">Thrown when the requested property does not exist.</exception> public static PropertyItem GetPropertyItem(this Image image, PropertyTag property) { if (image == null) { throw new ArgumentNullException(nameof(image)); } return(image.GetPropertyItem((int)property)); }
public GifHandler( Image Image ) { mImage = Image.Clone() as Image; mFrameDimension = new FrameDimension( mImage.FrameDimensionsList[ 0 ] ); mFrameCount = mImage.GetFrameCount( mFrameDimension ); mFrameTimes = new int[ mFrameCount ]; byte[] times = mImage.GetPropertyItem( 0x5100 ).Value; for( int i = 0; i < mFrameCount; i++ ) mFrameTimes[ i ] = BitConverter.ToInt32( times, 4 * i ) * 10; }
private static PropertyItem GetDateTakenPropertyItem(Image image) { PropertyItem dateTakenItem = null; try { dateTakenItem = image.GetPropertyItem(DATE_TAKEN); } catch (ArgumentException) { } return dateTakenItem; }
private static void SetPropertyItemString(Image srcImg, ImageMetadataPropertyId id, string value) { var buffer = Encoding.Unicode.GetBytes(value); var propItem = srcImg.GetPropertyItem(srcImg.PropertyItems[0].Id); propItem.Id = (int)id; propItem.Type = 1; propItem.Len = buffer.Length; propItem.Value = buffer; srcImg.SetPropertyItem(propItem); }
//------------------------------------------------------------------------------- // public ImageAnimation(Image img) { _image = img; FrameDimension = new FrameDimension(img.FrameDimensionsList[0]); MaxFrameCount = img.GetFrameCount(FrameDimension); PropertyItem pItemFrameDelay = img.GetPropertyItem(FRAME_DELAY); PropertyItem pItemFrameNum = img.GetPropertyItem(FRAME_NUM); FrameDelays = new int[MaxFrameCount]; for (int i = 0; i < MaxFrameCount; i++) { FrameDelays[i] = BitConverter.ToInt32(pItemFrameDelay.Value, 4 * i); } MaxLoopCount = BitConverter.ToInt16(pItemFrameNum.Value, 0); LoopInfinity = (MaxLoopCount == 0); _timer = new Timer(Timer_Elapsed, null, Timeout.Infinite, Timeout.Infinite); _image.SelectActiveFrame(FrameDimension, 0); }
/// <summary> /// Make sure the image is orientated correctly /// </summary> /// <param name="image"></param> public static void Orientate(Image image) { /*if (!conf.ProcessEXIFOrientation) { return; }*/ try { // Get the index of the orientation property. int orientationIndex = Array.IndexOf(image.PropertyIdList, EXIF_ORIENTATION_ID); // If there is no such property, return Unknown. if (orientationIndex < 0) { return; } PropertyItem item = image.GetPropertyItem(EXIF_ORIENTATION_ID); ExifOrientations orientation = (ExifOrientations)item.Value[0]; // Orient the image. switch (orientation) { case ExifOrientations.Unknown: case ExifOrientations.TopLeft: break; case ExifOrientations.TopRight: image.RotateFlip(RotateFlipType.RotateNoneFlipX); break; case ExifOrientations.BottomRight: image.RotateFlip(RotateFlipType.Rotate180FlipNone); break; case ExifOrientations.BottomLeft: image.RotateFlip(RotateFlipType.RotateNoneFlipY); break; case ExifOrientations.LeftTop: image.RotateFlip(RotateFlipType.Rotate90FlipX); break; case ExifOrientations.RightTop: image.RotateFlip(RotateFlipType.Rotate90FlipNone); break; case ExifOrientations.RightBottom: image.RotateFlip(RotateFlipType.Rotate90FlipY); break; case ExifOrientations.LeftBottom: image.RotateFlip(RotateFlipType.Rotate270FlipNone); break; } // Set the orientation to be normal, as we rotated the image. item.Value[0] = (byte)ExifOrientations.TopLeft; image.SetPropertyItem(item); } catch (Exception orientEx) { LOG.Warn("Problem orientating the image: ", orientEx); } }
public void getLatLong(System.Drawing.Image image) { try { PropertyItem p1 = image.GetPropertyItem(0x0001); byte[] array = new byte[p1.Len]; for (int i = 0; i < array.Length; i++) { array[i] = p1.Value[i]; } string sarray = Encoding.UTF8.GetString(array); PropertyItem p2 = image.GetPropertyItem(0x0002); lat = convertToCoordinates(p2); PropertyItem p3 = image.GetPropertyItem(0x0003); PropertyItem p4 = image.GetPropertyItem(0x0004); byte[] array1 = new byte[p1.Len]; for (int i = 0; i < array.Length; i++) { array1[i] = p3.Value[i]; } longi = convertToCoordinates(p4); string sarray1 = Encoding.UTF8.GetString(array1); if (sarray.Contains('S') || sarray.Contains('s')) { lat = -lat; } if (sarray1.Contains('W') || sarray1.Contains('w')) { longi = -longi; } int dasa = 3; gpsFound = true; } catch (Exception e) { //System.Windows.MessageBox.Show("No data found"); Console.WriteLine("No GPS data found"); Console.ReadLine(); } }
public GifImage(string path) { _lastRequest = DateTime.Now; _gifImage = Image.FromFile(path); //initialize _dimension = new FrameDimension(_gifImage.FrameDimensionsList[0]); //gets the GUID FrameCount = _gifImage.GetFrameCount(_dimension); //total frames in the animation Source = path; var item = _gifImage.GetPropertyItem(0x5100); // FrameDelay in libgdiplus _delay = (item.Value[0] + item.Value[1]*256)*10; // Time is in 1/100th of a second }
/// <summary> /// Return the image's orientation. /// </summary> /// <param name="img"></param> /// <returns></returns> public static ExifOrientations ImageOrientation(Image img) { // Get the index of the orientation property. int orientation_index = Array.IndexOf(img.PropertyIdList, OrientationID); // If there is no such property, return Unknown. if ((orientation_index < 0)) return ExifOrientations.Unknown; // Return the orientation value. return (ExifOrientations)img.GetPropertyItem(OrientationID).Value[0]; }
public void aperture_value(string path) { try { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) using (System.Drawing.Image myImage = System.Drawing.Image.FromStream(fs, false, false)) { PropertyItem propItem = myImage.GetPropertyItem(33437); //type 5 Fraction[] _resFraction = new Fraction[propItem.Len / (64 / 8)]; uint uNominator; uint uDenominator; for (int i = 0; i < _resFraction.Length; i++) { uNominator = BitConverter.ToUInt32(propItem.Value, i * (64 / 8)); uDenominator = BitConverter.ToUInt32(propItem.Value, i * (64 / 8) + (32 / 8)); _resFraction[i] = new Fraction(uNominator, uDenominator); } if (_resFraction.Length == 1) { string value = _resFraction[0].ToString(); string x, y; decimal s = 0; switch (value.Contains("/")) { case true: int start = value.IndexOf("/"); x = value.Substring(0, start); y = value.Substring(start + 1, value.Length - start - 1); s = Convert.ToDecimal(x) / Convert.ToDecimal(y); break; case false: s = Convert.ToDecimal(value); break; } aperturevalue = "f/" + s.ToString(); lblaperture_value.Text = aperturevalue; } else { lblaperture_value.Text = "- No Value"; aperturevalue = "- No Value"; } } } catch { lblaperture_value.Text = "- No Value"; aperturevalue = "- No Value"; } }
/// <summary> /// Attempts to get the <see cref="PropertyItem" /> specified by the <see cref="PropertyTag" />. /// </summary> /// <param name="image">The image to get the <see cref="PropertyItem" /> from.</param> /// <param name="propertyTag">The requested property.</param> /// <param name="propertyItem">The requested <see cref="PropertyItem" />.</param> /// <returns>True on success, false if the property does not exist.</returns> public static bool TryGetPropertyItem(this Image image, PropertyTag propertyTag, out PropertyItem propertyItem) { try { propertyItem = image.GetPropertyItem(propertyTag); return(true); } catch { propertyItem = null; return(false); } }
protected void MakeSureAllPropertyItemsArePresent(Image source, Image target) { foreach (var propertyItem in source.PropertyItems) { try { target.GetPropertyItem(propertyItem.Id); } catch (ArgumentException) { Assert.Fail("The property item with ID {0} was not present.", propertyItem.Id); } } }
/// <summary> /// <para>Conserta a rotação da imagem de acordo com a rotação original.</para> /// <para>Algumas imagens "importadas" tem a orientação diferente da definida no arquivo, este método conserta.</para> /// </summary> /// <param name="self">Stream de imagem</param> public static void FixToOriginalOrientation(this System.Drawing.Image self) { foreach (var prop in self.PropertyItems) { if (prop.Id == 0x0112) { int orientationValue = self.GetPropertyItem(prop.Id).Value[0]; RotateFlipType rotateFlipType = GetOrientationToFlipType(orientationValue); self.RotateFlip(rotateFlipType); prop.Value[0] = 1; self.SetPropertyItem(prop); break; } } }
public void camera_Model(string path) { try { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) using (System.Drawing.Image myImage = System.Drawing.Image.FromStream(fs, false, false)) { PropertyItem propItem = myImage.GetPropertyItem(272); cameraModel = Encoding.UTF8.GetString(propItem.Value); } lblcamera_Model.Text = cameraModel; } catch { lblcamera_Model.Text = "Null"; } }
protected void RotateAndResizeImage(string path) { System.Drawing.Image img = System.Drawing.Image.FromFile(path); int rotationPropertyID = 0x112; if (img.PropertyIdList.Contains(rotationPropertyID)) { PropertyItem rotationProperty = img.GetPropertyItem(rotationPropertyID); int rotationValue = BitConverter.ToUInt16(rotationProperty.Value, 0); RotateFlipType rotationToPerform = RotateFlipType.RotateNoneFlipNone; if (rotationValue == 3 || rotationValue == 4) { rotationToPerform = RotateFlipType.Rotate180FlipNone; } else if (rotationValue == 5 || rotationValue == 6) { rotationToPerform = RotateFlipType.Rotate90FlipNone; } else if (rotationValue == 7 || rotationValue == 8) { rotationToPerform = RotateFlipType.Rotate270FlipNone; } if (rotationValue == 2 || rotationValue == 4 || rotationValue == 5 || rotationValue == 7) { rotationToPerform |= RotateFlipType.RotateNoneFlipX; } if (rotationToPerform != RotateFlipType.RotateNoneFlipNone) { img.RotateFlip(rotationToPerform); } img.Save(path); } img.Dispose(); // Resizes the image to a better size for the decoder and also for the model ImageBuilder.Current.Build(path, path, new ResizeSettings("width=768&height=1024")); pnlImage.Visible = true; }
public static bool IsImageSrgbJpeg(System.Drawing.Image someImage) { try { var val = someImage.GetPropertyItem(34675); System.Drawing.Imaging.ImageFlags flagValues = (System.Drawing.Imaging.ImageFlags)Enum.Parse(typeof(System.Drawing.Imaging.ImageFlags), someImage.Flags.ToString()); return(flagValues.ToString().Contains("HasRealDpi")); } catch (ArgumentException ae) { return(true); } catch (Exception er) { return(false); } }
private void TryRotateImage(System.Drawing.Image inputImage) { try { if (inputImage.PropertyIdList.Contains(0x0112)) { var pro = inputImage.GetPropertyItem(0x0112); if (pro != null && pro.Value[0] == 6 && pro.Value[1] == 0) { inputImage.RotateFlip(RotateFlipType.Rotate90FlipNone); } } } catch (Exception ex) { LogHelper.TryLog("ImageService.TryRotateImage", ex); } }
/// <summary> /// Initializes a new instance of the <see cref="GifDecoder"/> class. /// </summary> /// <param name="image"> /// The <see cref="Image"/> to decode. /// </param> /// <param name="animationProcessMode"> /// The <see cref="AnimationProcessMode" /> to use. /// </param> public GifDecoder(Image image, AnimationProcessMode animationProcessMode) { this.Height = image.Height; this.Width = image.Width; if (FormatUtilities.IsAnimated(image) && animationProcessMode == AnimationProcessMode.All) { this.IsAnimated = true; this.FrameCount = image.GetFrameCount(FrameDimension.Time); // Loop info is stored at byte 20737. this.LoopCount = BitConverter.ToInt16(image.GetPropertyItem((int)ExifPropertyTag.LoopCount).Value, 0); } else { this.FrameCount = 1; } }
/// <summary> /// Returns the EXIF Image Data of the Date Taken. /// </summary> /// <param name="getImage">Image (If based on a file use Image.FromFile(f);)</param> /// <returns>Date Taken or Null if Unavailable</returns> public static DateTime? DateTaken(Image getImage) { int DateTakenValue = 0x9003; //36867; if (!getImage.PropertyIdList.Contains(DateTakenValue)) return null; string dateTakenTag = System.Text.Encoding.ASCII.GetString(getImage.GetPropertyItem(DateTakenValue).Value); string[] parts = dateTakenTag.Split(':', ' '); int year = int.Parse(parts[0]); int month = int.Parse(parts[1]); int day = int.Parse(parts[2]); int hour = int.Parse(parts[3]); int minute = int.Parse(parts[4]); int second = int.Parse(parts[5]); return new DateTime(year, month, day, hour, minute, second); }
public static System.Drawing.Image RotateImage(System.Drawing.Image imgSource) { if (Array.IndexOf(imgSource.PropertyIdList, 274) > -1) { var orientation = (int)imgSource.GetPropertyItem(274).Value[0]; switch (orientation) { case 1: // No rotation required. break; case 2: imgSource.RotateFlip(RotateFlipType.RotateNoneFlipX); break; case 3: imgSource.RotateFlip(RotateFlipType.Rotate180FlipNone); break; case 4: imgSource.RotateFlip(RotateFlipType.Rotate180FlipX); break; case 5: imgSource.RotateFlip(RotateFlipType.Rotate90FlipX); break; case 6: imgSource.RotateFlip(RotateFlipType.Rotate90FlipNone); break; case 7: imgSource.RotateFlip(RotateFlipType.Rotate270FlipX); break; case 8: imgSource.RotateFlip(RotateFlipType.Rotate270FlipNone); break; } // This EXIF data is now invalid and should be removed. imgSource.RemovePropertyItem(274); } return(imgSource); }
private void CorrectRotation(Image img) { if (Array.IndexOf(img.PropertyIdList, 274) > -1) { var orientation = (int)img.GetPropertyItem(274).Value[0]; switch (orientation) { case 1: // No rotation required. break; case 2: img.RotateFlip(RotateFlipType.RotateNoneFlipX); break; case 3: img.RotateFlip(RotateFlipType.Rotate180FlipNone); break; case 4: img.RotateFlip(RotateFlipType.Rotate180FlipX); break; case 5: img.RotateFlip(RotateFlipType.Rotate90FlipX); break; case 6: img.RotateFlip(RotateFlipType.Rotate90FlipNone); break; case 7: img.RotateFlip(RotateFlipType.Rotate270FlipX); break; case 8: img.RotateFlip(RotateFlipType.Rotate270FlipNone); break; } // This EXIF data is now invalid and should be removed. img.RemovePropertyItem(274); } }
public void taken_Date(string path) { try { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) using (System.Drawing.Image myImage = System.Drawing.Image.FromStream(fs, false, false)) { PropertyItem propItem = myImage.GetPropertyItem(36867); takendate = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2); lbltaken_Date.Text = takendate; } } catch { takendate = "- No Value"; lbltaken_Date.Text = "- No Value"; } }
// <summary> // Gets the date the picture was taken from. // </summary> // <param name="path"> The path of the file to be transfered. </param> // <returns> The date the picture was taken (upon success), // or picture creation date if an exception was caught. // </returns> private static DateTime GetDateTakenFromImage(string path) { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) using (System.Drawing.Image myImage = System.Drawing.Image.FromStream(fs, false, false)) { //tries to take the date the picture was taken from try { PropertyItem propItem = myImage.GetPropertyItem(36867); string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2); return(DateTime.Parse(dateTaken)); } //in case of exception, will return the creation time of the picture catch (Exception) { return(File.GetCreationTime(path)); } } }
/// <summary> /// 旋转图片到正确位置 /// </summary> /// <param name="image"></param> public static void OrientationImage(System.Drawing.Image image) { if (Array.IndexOf(image.PropertyIdList, 274) > -1) { var orientation = (int)image.GetPropertyItem(274).Value[0]; switch (orientation) { case 1: // No rotation required. break; case 2: image.RotateFlip(RotateFlipType.RotateNoneFlipX); break; case 3: image.RotateFlip(RotateFlipType.Rotate180FlipNone); break; case 4: image.RotateFlip(RotateFlipType.Rotate180FlipX); break; case 5: image.RotateFlip(RotateFlipType.Rotate90FlipX); break; case 6: image.RotateFlip(RotateFlipType.Rotate90FlipNone); break; case 7: image.RotateFlip(RotateFlipType.Rotate270FlipX); break; case 8: image.RotateFlip(RotateFlipType.Rotate270FlipNone); break; } image.RemovePropertyItem(274); } }
public void LoadGif(string gifPath) { gifImage = System.Drawing.Image.FromFile(gifPath); dimension = new FrameDimension(gifImage.FrameDimensionsList[0]); frameCount = gifImage.GetFrameCount(dimension); gifFrames = new Texture2D[frameCount]; gifFramesLock = new bool[frameCount]; for (int i = 0; i < frameCount; i++) { gifFramesLock[i] = false; } PropertyItem item = gifImage.GetPropertyItem(0x5100); // FrameDelay in libgdiplus delay = (item.Value[0] + item.Value[1] * 256) * 10; // Time is in 1/100ths of a second StartCoroutine(LoadFramesLoop()); }
/// <summary> /// Rotate the given bitmap according to Exif Orientation data /// </summary> /// <param name="img">source image</param> /// <param name="updateExifData">set it to TRUE to update image Exif data after rotation (default is TRUE)</param> /// <returns>The RotateFlipType value corresponding to the applied rotation. If no rotation occurred, RotateFlipType.RotateNoneFlipNone will be returned.</returns> public static RotateFlipType RotateImageByExifOrientationData(System.Drawing.Image img, bool updateExifData = true) { int orientationId = 0x0112; var fType = RotateFlipType.RotateNoneFlipNone; if (img.PropertyIdList.Contains(orientationId)) { var pItem = img.GetPropertyItem(orientationId); fType = GetRotateFlipTypeByExifOrientationData(pItem.Value[0]); if (fType != RotateFlipType.RotateNoneFlipNone) { img.RotateFlip(fType); // Remove Exif orientation tag (if requested) if (updateExifData) { img.RemovePropertyItem(orientationId); } } } return(fType); }
private static void ProcessingThread(byte[] gifData, AnimationInfo animationInfo) { System.Drawing.Image gifImage = System.Drawing.Image.FromStream(new MemoryStream(gifData)); FrameDimension dimension = new FrameDimension(gifImage.FrameDimensionsList[0]); int frameCount = gifImage.GetFrameCount(dimension); animationInfo.frameCount = frameCount; animationInfo.initialized = true; animationInfo.frames = new List <FrameInfo>(frameCount); int firstDelayValue = -1; var delays = gifImage.GetPropertyItem(20736).Value; for (int i = 0; i < frameCount; i++) { gifImage.SelectActiveFrame(dimension, i); using (Bitmap bitmap = new Bitmap(gifImage)) { bitmap.MakeTransparent(System.Drawing.Color.Black); bitmap.RotateFlip(RotateFlipType.Rotate180FlipX); BitmapData frame = bitmap.LockBits(new Rectangle(Point.Empty, gifImage.Size), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); FrameInfo currentFrame = new FrameInfo(frame.Width, frame.Height); Marshal.Copy(frame.Scan0, currentFrame.colors, 0, currentFrame.colors.Length); int delayPropertyValue = BitConverter.ToInt32(delays, i * 4); if (firstDelayValue == -1) { firstDelayValue = delayPropertyValue; } currentFrame.delay = delayPropertyValue * 10; animationInfo.frames.Add(currentFrame); } } }
public static void ImageRotation(Image img) { if (Array.IndexOf(img.PropertyIdList, 274) > -1) { var orientation = (int)img.GetPropertyItem(274).Value[0]; switch (orientation) { case 1: // No rotation required. break; case 2: img.RotateFlip(RotateFlipType.RotateNoneFlipX); break; case 3: img.RotateFlip(RotateFlipType.Rotate180FlipNone); break; case 4: img.RotateFlip(RotateFlipType.Rotate180FlipX); break; case 5: img.RotateFlip(RotateFlipType.Rotate90FlipX); break; case 6: img.RotateFlip(RotateFlipType.Rotate90FlipNone); break; case 7: img.RotateFlip(RotateFlipType.Rotate270FlipX); break; case 8: img.RotateFlip(RotateFlipType.Rotate270FlipNone); break; } // This EXIF data is now invalid and should be removed. //img.RemovePropertyItem(274); } }
public Image RotateImage(Image bmp) { if (Array.IndexOf(bmp.PropertyIdList, 274) > -1) { var orientation = (int)bmp.GetPropertyItem(274).Value[0]; switch (orientation) { case 1: // No rotation required. break; case 2: bmp.RotateFlip(RotateFlipType.RotateNoneFlipX); break; case 3: bmp.RotateFlip(RotateFlipType.Rotate180FlipNone); break; case 4: bmp.RotateFlip(RotateFlipType.Rotate180FlipX); break; case 5: bmp.RotateFlip(RotateFlipType.Rotate90FlipX); break; case 6: bmp.RotateFlip(RotateFlipType.Rotate90FlipNone); break; case 7: bmp.RotateFlip(RotateFlipType.Rotate270FlipX); break; case 8: bmp.RotateFlip(RotateFlipType.Rotate270FlipNone); break; } // This EXIF data is now invalid and should be removed. bmp.RemovePropertyItem(274); } return bmp; }
private static PropertyItem CreateProperty(Image image, int id, int length, short type, byte[] value) { try { PropertyItem item = image.GetPropertyItem(image.PropertyIdList[0]); item.Id = id; item.Len = length; item.Type = type; item.Value = value; return item; } catch (Exception) { throw; } }
/// <summary> /// /// </summary> /// <param name="image"></param> /// <returns></returns> public static ImageExif GetExifInfo(Image image) { //http://www.exiv2.org/tags.html ImageExif exif = new ImageExif(); List<ExifProperty> properties = new List<ExifProperty>(); exif.RawFormatID = image.RawFormat.Guid; foreach (int hex in image.PropertyIdList) { var exit = new ExifProperty(image.GetPropertyItem(hex)); properties.Add(exit); switch ((int)hex) { case 274: { var value = Convert.ToUInt16(exit.DisplayValue); if (value != 0) exif.Orientation = ObjectUtility.Cast<Orientation>(value); break; } case 40091: exif.Title = ObjectUtility.Cast<string>(exit.DisplayValue); break; case 40092: exif.Comment = GetStringUnicode(image, hex); break; case 40093: exif.Author = ObjectUtility.Cast<string>(exit.DisplayValue); break; case 40094: exif.Keyword = GetStringUnicode(image, hex); break; case 40095: exif.Subject = GetStringUnicode(image, hex); break; case 33432: exif.Copyright = ObjectUtility.Cast<string>(exit.DisplayValue); break; case 270: exif.Description = ObjectUtility.Cast<string>(exit.DisplayValue); break; case 271: exif.EquipmentMake = ObjectUtility.Cast<string>(exit.DisplayValue); break; case 272: exif.EquipmentModel = ObjectUtility.Cast<string>(exit.DisplayValue); break; case 34850: { var value = ObjectUtility.Cast<short>(exit.DisplayValue); exif.ExposureProgram = ObjectUtility.Cast<ExposurePrograms>(value); ; break; } case 34855: exif.ISOSpeedRatings = ObjectUtility.Cast<short>(exit.DisplayValue); break; case 37384: exif.Flash = ObjectUtility.Cast<short>(exit.DisplayValue); break; case 37385: exif.LightSource = ObjectUtility.Cast<short>(exit.DisplayValue); break; case 37383: exif.MeteringMode = ObjectUtility.Cast<int>(exit.DisplayValue); break; case 18246: exif.Rating = ObjectUtility.Cast<short>(exit.DisplayValue); break; case 41987: exif.WhiteBalance = ObjectUtility.Cast<short>(exit.DisplayValue); break; case 41992: exif.Contrast = ObjectUtility.Cast<short>(exit.DisplayValue); break; case 41993: exif.Saturation = ObjectUtility.Cast<short>(exit.DisplayValue); break; case 41994: exif.Sharpness = ObjectUtility.Cast<short>(exit.DisplayValue); break; case 33434: exif.ExposureTime =Rational.GetRational(exit.Value) ; break; case 41989: exif.FocalLengthIn35mmFilm = ObjectUtility.Cast<short>(exit.DisplayValue); break; case 36867: exif.DateTimeOriginal = GetDateTime(image, hex); break; case 37377: exif.ShutterSpeed = GetDouble(image, hex); break; case 36868: exif.DateTimeDigitized = GetDateTime(image, hex); break; case 36864: exif.ExifVersion = ObjectUtility.Cast<string>(exit.DisplayValue); break; case 531: exif.YCbCrPositioning = ObjectUtility.Cast<short>(exit.DisplayValue); break; case 20625: exif.ChrominanceTable = ObjectUtility.Cast<short>(exit.DisplayValue); break; case 20624: exif.LuminanceTable = ObjectUtility.Cast<short>(exit.DisplayValue); break; case 20507: exif.ThumbnailData = image.GetPropertyItem(hex).Value; break; case 20528: exif.ThumbnailResolutionUnit = ObjectUtility.Cast<short>(exit.DisplayValue); break; case 20515: exif.ThumbnailCompression = ObjectUtility.Cast<short>(exit.DisplayValue); break; case 296: exif.ResolutionUnit = ObjectUtility.Cast<short>(exit.DisplayValue); break; case 282: case 283: { var unit = exif.ResolutionUnit; if (unit == 0 && image.PropertyIdList.Contains(296)) { unit = GetInt(image, 296); } var r = (unit == 3) ? 2.54f : 1f; if (exif.Resolution == null && image.PropertyIdList.Contains(282) && image.PropertyIdList.Contains(283)) exif.Resolution = new SizeF(r * GetInt(image, 282), r * GetInt(image, 283)); break; } case 20525: case 20526: { if (exif.Pix == null && image.PropertyIdList.Contains(20525) && image.PropertyIdList.Contains(20526)) exif.ThumbnailResolution = new Size(GetInt(image, 20525), GetInt(image, 20526)); break; } case 40962: case 40963: { if (exif.Pix == null && image.PropertyIdList.Contains(40962) && image.PropertyIdList.Contains(40963)) exif.Pix = new Size(GetInt(image, 40962), GetInt(image, 40963)); break; } case 1: case 2: case 3: case 4: case 5: case 6: case 29: { if (image.PropertyIdList.Contains(1) && image.PropertyIdList.Contains(2)) { if (exif.GPS == null) { exif.GPS = new GPSGeo() { LatitudeRef = GetStringAsc(image, 1), Latitude = GetDouble(image, 2), }; } else { exif.GPS.LatitudeRef = GetStringAsc(image, 1); exif.GPS.Latitude = GetDouble(image, 2); } } if (image.PropertyIdList.Contains(3) && image.PropertyIdList.Contains(4)) { if (exif.GPS == null) { exif.GPS = new GPSGeo() { LongitudeRef = GetStringAsc(image, 3), Longitude = GetDouble(image, 4), }; } else { exif.GPS.LongitudeRef = GetStringAsc(image, 3); exif.GPS.Longitude = GetDouble(image, 4); } } if (image.PropertyIdList.Contains(5) && image.PropertyIdList.Contains(6)) { if (exif.GPS == null) { exif.GPS = new GPSGeo() { AltitudeRef = GetStringAsc(image, 5), Altitude = GetDouble(image, 6), }; } else { exif.GPS.AltitudeRef = GetStringAsc(image, 5); exif.GPS.Altitude = GetDouble(image, 6); } } if (image.PropertyIdList.Contains(29)) { if (exif.GPS == null) { exif.GPS = new GPSGeo() { DateStamp = DateTime.ParseExact(GetStringAsc(image, 29), "yyyy:MM:dd", null) }; } else { exif.GPS.DateStamp = DateTime.ParseExact(GetStringAsc(image, 29), "yyyy:MM:dd", null); } } break; } } } exif.Properties = new ExifPropertyCollection(properties); return exif; }
/// <summary> /// /// </summary> /// <param name="image"></param> private void LoadFrames(Image image) { int framesCount = image.GetFrameCount(FrameDimension.Time); if (framesCount <= 1) { throw new ArgumentException("Image not animated"); } byte[] times = image.GetPropertyItem(0x5100).Value; int frame = 0; List<AnimationGifFrame> frames = new List<AnimationGifFrame>(); while (true) { int dur = BitConverter.ToInt32(times, 4 * frame) * 10; frames.Add(new AnimationGifFrame(new Bitmap(image), dur)); if (++frame >= framesCount) break; image.SelectActiveFrame(FrameDimension.Time, frame); } this._frames = frames.ToArray(); }
private static DateTime? GetDateTime(Image getImage, int hex) { string dateTakenTag = Encoding.ASCII.GetString(getImage.GetPropertyItem(hex).Value); if (dateTakenTag == null || dateTakenTag.Contains("0000:00:00 00:00:00")) return null; string[] parts = dateTakenTag.Split(':', ' '); int year = int.Parse(parts[0]); int month = int.Parse(parts[1]); int day = int.Parse(parts[2]); int hour = int.Parse(parts[3]); int minute = int.Parse(parts[4]); int second = int.Parse(parts[5]); if (year == 0 || month == 0 || day == 0) return null; return new DateTime(year, month, day, hour, minute, second); }
private DateTime GetDateTaken(Image targetImg) { //Property Item 36867 corresponds to the Date Taken PropertyItem propItem = targetImg.GetPropertyItem(36867); DateTime dtaken; //Convert date taken metadata to a DateTime object string sdate = Encoding.UTF8.GetString(propItem.Value).Trim(); string secondhalf = sdate.Substring(sdate.IndexOf(" "), (sdate.Length - sdate.IndexOf(" "))); string firsthalf = sdate.Substring(0, 10); firsthalf = firsthalf.Replace(":", "-"); sdate = firsthalf + secondhalf; dtaken = DateTime.Parse(sdate); return dtaken; }
private static short GetShort(Image getImage, int hex) { var propety = getImage.GetPropertyItem(hex); // if (propety.Type != 5) return 0; var value = propety.Value; if (propety.Value.Length == 2) return BitConverter.ToInt16(value, 0); return 0; }
private static double GetDouble(Image getImage, int hex) { var propety = getImage.GetPropertyItem(hex); // if (propety.Type != 5) return 0; var value = propety.Value; switch (propety.Value.Length) { case 2: return BitConverter.ToInt16(value, 0); case 4: return BitConverter.ToUInt32(value, 0); case 24: { float degrees = BitConverter.ToUInt32(value, 0) / (float)BitConverter.ToUInt32(value, 4); float minutes = BitConverter.ToUInt32(value, 8) / (float)BitConverter.ToUInt32(value, 12); float seconds = BitConverter.ToUInt32(value, 16) / (float)BitConverter.ToUInt32(value, 20); float coorditate = degrees + (minutes / 60f) + (seconds / 3600f); return coorditate; } case 8: { return BitConverter.ToUInt32(value, 0) / (float)BitConverter.ToUInt32(value, 4); } } return 0; }
private static string GetStringUnicode(Image getImage, int hex) { string dateTakenTag = Encoding.Unicode.GetString(getImage.GetPropertyItem(hex).Value); return dateTakenTag.Replace("\0", string.Empty); }
//Bonus. A simple check on the GIF files because some may contain "bad" data and crash the program. public static bool isImageCorrupted(Image img) { bool itis = false; try { if (!ImageAnimator.CanAnimate(img)) { return itis; } int frames = img.GetFrameCount(System.Drawing.Imaging.FrameDimension.Time); if (frames <= 1) { return itis; } byte[] times = img.GetPropertyItem(0x5100).Value; int frame = 0; for (; ; ) { int dur = BitConverter.ToInt32(times, 4 * frame); if (++frame >= frames) break; img.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Time, frame); } } catch (Exception ex) { throw ex; } return itis; }
public float? GetLatitude(Image targetImg) { try { //Property Item 0x0001 - PropertyTagGpsLatitudeRef PropertyItem propItemRef = targetImg.GetPropertyItem(1); //Property Item 0x0002 - PropertyTagGpsLatitude PropertyItem propItemLat = targetImg.GetPropertyItem(2); //https://cberio.blob.core.windows.net/photo/collection01/20150723_101520.jpg //https://cberio.blob.core.windows.net/photo/collection01/20150722_234712.jpg //System.Diagnostics.Debug.WriteLine("==== Orient = " + targetImg.GetPropertyItem(274).Value[0]); return ExifGpsToFloat(propItemRef, propItemLat); } catch (ArgumentException) { return null; } finally { //if (targetImg != null) // targetImg.Dispose(); } }
public static object GetPropertyValue(Image image, PropertyTag tag) { if (image == null) { throw new ArgumentNullException(); } try { return GetPropertyValue(image.GetPropertyItem((int) tag)); } catch (ArgumentException) { return null; } }
public static object GetImagePropertyValue(Image image, PropertyTagId tagId) { object result = null; PropertyItem propertyItem = null; try { propertyItem = image.GetPropertyItem((int)tagId); } catch (ArgumentException) { } if (propertyItem != null) { return GetImagePropertyValue(propertyItem); } return result; }