/// <summary> /// Returning an int so I dont need to link exif into the native apps. /// </summary> /// <param name="imgBits"></param> /// <returns></returns> public static int readExifOrientation(byte[] imgBits) { ExifOrientation result = ExifOrientation.Undefined; if (imgBits != null) { using (var resource = new MemoryStream(imgBits)) { try { JpegInfo jpegInfo = ExifReader.ReadJpeg(resource); // What exif lib associates each orientation with num in spec: // ExifLib.ExifOrientation.TopRight == 6; // i need to rotate clockwise 90 // ExifLib.ExifOrientation.BottomLeft == 8; // i need to rotate ccw 90 // ExifLib.ExifOrientation.BottomRight == 3; // i need to rotate 180 // ExifLib.ExifOrientation.TopLeft ==1; // do nada. // What each image I set the exif on resulted in: // (note: what I set should be correct as it displays right in programs that adjust for exif) // Unchd: 1 // ImgRotLeft: 6 // ImgRotRight: 8 // ImgRot180: 3 // Cool. These all tie out with images in Dave Perret article. result = jpegInfo.Orientation; //int imgExifWidth = jpegInfo.Width; //int imgExifHeight = jpegInfo.Height; Debug.WriteLine("DHB:GlobalSingletonHelpers:readExifOrientation orientation:" + result); } catch (Exception e) { Debug.WriteLine("DHB:GlobalSingletonHelpers:readExifOrientation bad exif read"); Debug.WriteLine(e.ToString()); } } } return((int)result); }
public static Stream HandleOrientation(Stream stream, string fileName) { // figure out the orientation from EXIF data stream.Position = 0; JpegInfo info = ExifReader.ReadJpeg(stream, fileName); var angle = 0; switch (info.Orientation) { case ExifOrientation.TopLeft: case ExifOrientation.Undefined: angle = 0; break; case ExifOrientation.TopRight: angle = 90; break; case ExifOrientation.BottomRight: angle = 180; break; case ExifOrientation.BottomLeft: angle = 270; break; } if (angle > 0d) { stream = RotateStream(stream, angle); } stream.Seek(0, SeekOrigin.Begin); return(stream); }
private async Task <string[]> ResizeAsync(string filePath) { var str = new string[2]; string folder = Path.GetDirectoryName(filePath) + "/"; string img = folder + "R" + Path.GetFileName(filePath); string thumb = folder + "T" + Path.GetFileName(filePath); IFile vf = await FileSystem.Current.GetFileFromPathAsync(filePath); using (Stream stream = await vf.OpenAsync(PCLStorage.FileAccess.Read)) { JpegInfo exif = ExifReader.ReadJpeg(stream); int width = 0; int height = 0; int thumbWidth = 0; int thumbHigh = 0; if (exif.Width > 0) { width = exif.Width; height = exif.Height; if (width > height) { var temp = width; width = height; height = temp; _landscape = true; } } else { width = 1000; height = 2000; } if (exif.Width / 7 < 100) { thumbWidth = 70; thumbHigh = 100; } else { thumbWidth = width / 7; thumbHigh = height / 13; } _imageService.ResizeImage(filePath, img, width, height); _imageService.ResizeImage(filePath, thumb, thumbWidth, thumbHigh); str[0] = img; str[1] = thumb; } return(str); }
public ExifImage(BitmapImage imageSource, JpegInfo info) { PixelWidth = imageSource.PixelWidth; PixelHeight = imageSource.PixelHeight; AspectRatio = (double)PixelWidth / (double)PixelHeight; Image = new Image(); Image.Source = imageSource; ImageInfo = info; }
public static JpegInfo ReadJpeg(Stream FileStream, string FileName) { DateTime now = DateTime.Now; JpegInfo info = ExifReader.ReadJpeg(FileStream, FileName); info.FileSize = (int)FileStream.Length; info.FileName = string.Format("{0}.jpg", FileName); info.LoadTime = (TimeSpan)(DateTime.Now - now); return(info); }
private void GetPhotoTaskCompleted(object sender, PhotoResult e) { if (getPhotoCallback != null) { if (e.TaskResult == TaskResult.OK) { JpegInfo info = ExifReader.ReadJpeg(e.ChosenPhoto, e.OriginalFileName); e.ChosenPhoto.Seek(0, SeekOrigin.Begin); ExifOrientation _orientation = info.Orientation; int _angle = 0; switch (info.Orientation) { case ExifOrientation.TopLeft: case ExifOrientation.Undefined: _angle = 0; break; case ExifOrientation.TopRight: _angle = 90; break; case ExifOrientation.BottomRight: _angle = 180; break; case ExifOrientation.BottomLeft: _angle = 270; break; } Stream capturedImage; if (_angle > 0d) { capturedImage = RotateStream(e.ChosenPhoto, _angle); } else { capturedImage = e.ChosenPhoto; } IMobeelizerFile file = Mobeelizer.CreateFile("photo", capturedImage); this.getPhotoCallback(file); this.getPhotoCallback = null; } else { this.GetPhoto(getPhotoCallback); } } }
private void AddImage(FileInfo fi) { try { DateTime then = DateTime.Now; JpegInfo info = ExifReader.ReadJpeg(fi); BitmapImage img = new BitmapImage(); if (info.ThumbnailData != null) { // the fast way - using the Exif thumbnail for preview MemoryStream ms = new MemoryStream(info.ThumbnailData); img.SetSource(ms); } else { // the slow and expensive way - loading a monster image in memory img.CreateOptions = BitmapCreateOptions.None; using (FileStream fs = fi.OpenRead()) { img.SetSource(fs); fs.Close(); } } info.LoadTime = (DateTime.Now - then); ExifImage image = new ExifImage(img, info); ImageCanvas.Children.Add(image.Image); int oldCount = mImages.Count; mImages.Add(image); if (oldCount == 0) { UpdateImageInfo(); } } catch (OutOfMemoryException) { HtmlPage.Window.Alert("You are out of memory. No more images will be loaded."); throw; } catch (Exception e) { // well that sucks. HtmlPage.Window.Alert("An error occured:\r\n" + e.ToString()); } // this could be expensive, try to clean up as we go... GC.Collect(); }
ImageInfo CopyImage(ImageInfo dbInfo) { string filePath = dbInfo.OldPath; JpegInfo imageInfo = null; string newFilePath = ""; bool usedExif = false; using (var stream = _fileService.GetFileStream(filePath)) { imageInfo = ExifReader.ReadJpeg(stream); } if (imageInfo != null && (!string.IsNullOrEmpty(imageInfo.DateTime) || !string.IsNullOrEmpty(imageInfo.DateTimeOriginal))) { if (!string.IsNullOrEmpty(imageInfo.DateTimeOriginal)) { var dtOriginal = DateTime.ParseExact(imageInfo.DateTimeOriginal, _exifDateFormat, CultureInfo.InvariantCulture); dbInfo.DateTaken = dtOriginal; } if (!string.IsNullOrEmpty(imageInfo.DateTime)) { var dtOriginal = DateTime.ParseExact(imageInfo.DateTime, _exifDateFormat, CultureInfo.InvariantCulture); dbInfo.DateModified = dtOriginal; } var realDate = imageInfo.DateTimeOriginal ?? imageInfo.DateTime; dbInfo.FinalModified = ParseDate(realDate); usedExif = true; } else { var attrs = File.GetAttributes(filePath); var dtCreation = File.GetCreationTimeUtc(filePath); dbInfo.DateModified = dtCreation; dbInfo.FinalModified = ParseDate(dtCreation.ToString(_exifDateFormat)); //newFilePath = Path.Combine(_backupPath, _noExifBaseFolder, _shouldReplacePath ? filePath.Replace(_pathToReplace, "") : filePath); } newFilePath = GetFilePathFromDate(filePath, newFilePath, dbInfo.FinalModified); newFilePath = Path.Combine(newFilePath, Path.GetFileName(filePath)); dbInfo.ExifInfo = imageInfo.ToString(); dbInfo.DateParsed = DateTime.Now; dbInfo.NewPath = newFilePath; CopyFile(filePath, newFilePath, usedExif); return(dbInfo); }
void picker_Completed(object sender, PhotoResult e) { tookPhoto = false; if (e.ChosenPhoto == null) { return; } e.ChosenPhoto.Position = 0; JpegInfo info = ExifReader.ReadJpeg(e.ChosenPhoto, e.OriginalFileName); /** * get image location */ lat = info.GpsLatitude[0]; lng = info.GpsLongitude[0]; if (info.GpsLatitudeRef == ExifGpsLatitudeRef.South) { lat = lat * -1; } if (info.GpsLongitudeRef == ExifGpsLongitudeRef.West) { lng = lng * -1; } /////////////////////// bmp.SetSource(e.ChosenPhoto); captured.Source = bmp; Dispatcher.BeginInvoke(() => { /** * determine if picture is Portrait or Landscape */ if ((Convert.ToDouble(bmp.PixelHeight) / Convert.ToDouble(bmp.PixelWidth)) < 1) { NavigationService.Navigate(new Uri("/CropPageLandscapeOrientation.xaml", UriKind.Relative)); } else { NavigationService.Navigate(new Uri("/CropPage.xaml", UriKind.Relative)); } }); }
public async Task CreateAndStoreDatumAsync(string path, string mimeType, DateTime timestamp) { if (File.Exists(path)) { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { string imageBase64 = null; if (mimeType == JPEG_MIME_TYPE) { JpegInfo info = ExifReader.ReadJpeg(fs); double latitude = 0; double longitude = 0; if (info.GpsLatitude != null && info.GpsLongitude != null) { latitude = (Math.Truncate(info.GpsLatitude[0]) + (info.GpsLatitude[1] / 60) + (info.GpsLatitude[2] / 3600)) * (info.GpsLatitudeRef == ExifGpsLatitudeRef.North ? 1 : -1); longitude = (Math.Truncate(info.GpsLongitude[0]) + (info.GpsLongitude[1] / 60) + (info.GpsLongitude[2] / 3600)) * (info.GpsLongitudeRef == ExifGpsLongitudeRef.East ? 1 : -1); } if (StoreImages) { fs.Position = 0; imageBase64 = Convert.ToBase64String(await ReadFile(fs)); } await StoreDatumAsync(new ImageMetadataDatum(info.FileSize, info.Width, info.Height, (int)info.Orientation, info.XResolution, info.YResolution, (int)info.ResolutionUnit, info.IsColor, (int)info.Flash, info.FNumber, info.ExposureTime, info.Software, latitude, longitude, mimeType, imageBase64, timestamp)); } else // the file is something else... { if (StoreVideos || (StoreImages && mimeType.StartsWith(IMAGE_DISCRETE_TYPE))) { fs.Position = 0; imageBase64 = Convert.ToBase64String(await ReadFile(fs)); } await StoreDatumAsync(new ImageMetadataDatum((int)fs.Length, null, null, null, null, null, null, null, null, null, null, null, null, null, mimeType, imageBase64, timestamp)); } } } }
void OnImageReceived_android(ImageData data) { Debug.LogError("OnImageReceived"); JpegInfo jpegInfo = ExifReader.ReadJpegFromBytes(data.data, ""); Debug.LogError("jpegInfo.IsValid=" + jpegInfo.IsValid + " " + jpegInfo.Width + " " + jpegInfo.Height); Debug.LogError("jpegInfo.Orientation=" + jpegInfo.Orientation); Debug.LogError("width=" + data.width + " height=" + data.height); Debug.LogError("filePath=" + data.filePath); Debug.LogError("Application.persistentDataPath=" + Application.persistentDataPath); SetImageTexture(PhotoPicker.GetTexture2DFromImageData(data)); imagePath = data.filePath; if (!File.Exists(imagePath)) { File.WriteAllBytes(imagePath, data.data); } }
void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { if (e.Error == null) { var stream = e.Result; JpegInfo info = ExifReader.ReadJpeg(stream, "victory"); if (info.Height > info.Width) { stream = RotateStream(stream, 90); } Deployment.Current.Dispatcher.BeginInvoke(() => { var bitmap = new BitmapImage(); bitmap.SetSource(stream); MainImage.Source = bitmap; }); } }
void testLocalPhoto2() { object textureObj = Resources.Load("test2", typeof(Texture2D)); Texture2D texture = (Texture2D)textureObj; //texture.anisoLevel = 1; //texture.filterMode = FilterMode.Bilinear; //texture.wrapMode = TextureWrapMode.Clamp; //scale to small size int aScaleSize = MediaBase.getAScaleSize(texture.width); TextureScale.Bilinear(texture, texture.width / aScaleSize, texture.height / aScaleSize); JpegInfo jpi = ExifReader.ReadJpeg(texture.EncodeToJPG(), "Foo"); int angle = 0; switch (jpi.Orientation) { case ExifOrientation.TopLeft: break; case ExifOrientation.TopRight: angle = -90; break; case ExifOrientation.BottomLeft: angle = 90; break; case ExifOrientation.BottomRight: angle = 180; break; } texture = TextureRotate.RotateImage(texture, angle); Sprite picture = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero, 1); PictureLoaded(true, "", picture); }
public static void AddJpegToPage(IntPtr document, IntPtr page, Image image, BoundsInches imageBounds, int transformationIndex) { byte[] buffer = Utils.Imaging.ByteArrayFromImage(image); // imageBounds are dimensions of transformed image (as displayed) TransformationMatrix matrix = GetTransformationMatrix(imageBounds, transformationIndex); unsafe { fixed(byte* p = buffer) { JpegInfo info = new JpegInfo(); info.Height = image.Height; info.Width = image.Width; info.Data = (IntPtr)p; info.Size = buffer.Length; Pdfium.AddJpegImageToPage(document, page, &info, &matrix); } } }
IEnumerator LoadPictureCoroutine(string path) { WWW www = new WWW(path); if (www.size == 0) { showlog("size 0"); yield return(new WaitForSeconds(1.0f)); LoadPicture(path); } else if (!string.IsNullOrEmpty(www.error)) { showlog("error"); PictureLoaded(false, null, null); } else { //ExifLib.JpegInfo jpi = ExifLib.ExifReader.ReadJpeg(www.bytes, "test2.jpg"); //showlog("EXIF: " + jpi.Orientation); //Texture2D texture = new Texture2D(www.texture.width, www.texture.height, TextureFormat.RGB24, false); //texture.anisoLevel = 1; //texture.filterMode = FilterMode.Bilinear; //texture.wrapMode = TextureWrapMode.Clamp; //www.LoadImageIntoTexture(texture); //TextureScale.Bilinear(texture, texture.width / 5, texture.height / 5); //texture = TextureRotate.RotateImage(texture, -90); Texture2D texture = new Texture2D(www.texture.width, www.texture.height, TextureFormat.RGB24, false); texture.anisoLevel = 1; texture.filterMode = FilterMode.Bilinear; texture.wrapMode = TextureWrapMode.Clamp; www.LoadImageIntoTexture(texture); //scale to small size int aScaleSize = MediaBase.getAScaleSize(texture.width); TextureScale.Bilinear(texture, texture.width / aScaleSize, texture.height / aScaleSize); JpegInfo jpi = ExifReader.ReadJpeg(www.bytes, "Foo"); int angle = 0; switch (jpi.Orientation) { case ExifOrientation.TopLeft: break; case ExifOrientation.TopRight: angle = -90; break; case ExifOrientation.BottomLeft: angle = 90; break; case ExifOrientation.BottomRight: angle = 180; break; } texture = TextureRotate.RotateImage(texture, angle); Sprite picture = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero, 1); PictureLoaded(true, path, picture); } }
public static SKBitmap buildFixedRotationSKBitmapFromBytes(byte[] imgBits, ExifOrientation imgExifO = ExifOrientation.Undefined) { SKBitmap rotatedBmp = null; if (imgBits != null) { DateTime step0 = DateTime.Now; using (var resource = new MemoryStream(imgBits)) { //using (var stream = new SKManagedStream(resource)) { //using (var stream = new MemoryStream((resource)) { DateTime step1 = DateTime.Now; if (imgExifO == ExifOrientation.Undefined) { imgExifO = ExifLib.ExifOrientation.TopLeft; try { JpegInfo jpegInfo = ExifReader.ReadJpeg(resource); // What exif lib associates each orientation with num in spec: // ExifLib.ExifOrientation.TopRight == 6; // i need to rotate clockwise 90 // ExifLib.ExifOrientation.BottomLeft == 8; // i need to rotate ccw 90 // ExifLib.ExifOrientation.BottomRight == 3; // i need to rotate 180 // ExifLib.ExifOrientation.TopLeft ==1; // do nada. // What each image I set the exif on resulted in: // (note: what I set should be correct as it displays right in programs that adjust for exif) // Unchd: 1 // ImgRotLeft: 6 // ImgRotRight: 8 // ImgRot180: 3 // Cool. These all tie out with images in Dave Perret article. imgExifO = jpegInfo.Orientation; //int imgExifWidth = jpegInfo.Width; //int imgExifHeight = jpegInfo.Height; //string res = "Orient:" + imgExifO.ToString() + " W:" + imgExifWidth + ", H:" + imgExifHeight; //string res2 = res + "dummy"; } catch (Exception e) { Debug.WriteLine("DHB:GlobalSingletonHelpers:buildFixedRotationSKBitmapFromBytes bad exif read"); Debug.WriteLine(e.ToString()); } } DateTime step2 = DateTime.Now; try { SKBitmap baseBmp = SKBitmapFromBytes(imgBits); //SKBitmap rotatedBmp = null; if (imgExifO == ExifLib.ExifOrientation.TopRight) { rotatedBmp = new SKBitmap(baseBmp.Height, baseBmp.Width); using (var canvas = new SKCanvas(rotatedBmp)) { canvas.Translate(rotatedBmp.Width, 0); canvas.RotateDegrees(90); canvas.DrawBitmap(baseBmp, 0, 0); } } else if (imgExifO == ExifLib.ExifOrientation.BottomLeft) { rotatedBmp = new SKBitmap(baseBmp.Height, baseBmp.Width); using (var canvas = new SKCanvas(rotatedBmp)) { // currently upside down. with w, 90. // failures: -W, 270 w,-90 -W,90 0,90 0,270 // h, 270 -> soln is to think about the corner I'm told is important... //canvas.Translate(-rotatedBmp.Width, 0); canvas.Translate(0, rotatedBmp.Height); canvas.RotateDegrees(270); canvas.DrawBitmap(baseBmp, 0, 0); } } else if (imgExifO == ExifLib.ExifOrientation.BottomRight) { rotatedBmp = new SKBitmap(baseBmp.Width, baseBmp.Height); using (var canvas = new SKCanvas(rotatedBmp)) { canvas.Translate(rotatedBmp.Width, rotatedBmp.Height); canvas.RotateDegrees(180); canvas.DrawBitmap(baseBmp, 0, 0); } } else { rotatedBmp = baseBmp; } Debug.WriteLine("DHB:GlobalSingletonHelpers:buildFixedRotationSKBitmapFromBytes success"); } catch (Exception e) { string msg = e.ToString(); } DateTime step3 = DateTime.Now; //Debug.WriteLine("DHB:GlobalSingletonHelpers:buildFixedRotationSKBitmapFromBytes step1:" + (step1 - step0)); //Debug.WriteLine("DHB:GlobalSingletonHelpers:buildFixedRotationSKBitmapFromBytes step2:" + (step2 - step1)); //Debug.WriteLine("DHB:GlobalSingletonHelpers:buildFixedRotationSKBitmapFromBytes step3:" + (step3 - step2)); } } return(rotatedBmp); }
private IEnumerator LoadPictureCoroutine(string path) { _count--; #if !UNITY_EDITOR && !UNITY_WEBGL path = "file://" + path; #endif WWW www = new WWW(path); yield return(www); if (www.size == 0) { yield return(new WaitForSeconds(1.0f)); LoadPicture(path); } else if (!string.IsNullOrEmpty(www.error)) { PictureLoaded(false, null, null); } else { Texture2D texture = new Texture2D(www.texture.width, www.texture.height, TextureFormat.RGB24, false); texture.anisoLevel = 1; texture.filterMode = FilterMode.Bilinear; texture.wrapMode = TextureWrapMode.Clamp; www.LoadImageIntoTexture(texture); //scale to small size int aScaleSize = getAScaleSize(texture.width); TextureScale.Bilinear(texture, texture.width / aScaleSize, texture.height / aScaleSize); JpegInfo jpi = ExifReader.ReadJpeg(www.bytes, "Foo"); int angle = 0; switch (jpi.Orientation) { case ExifOrientation.TopLeft: break; case ExifOrientation.TopRight: angle = -90; break; case ExifOrientation.BottomLeft: angle = 90; break; case ExifOrientation.BottomRight: angle = 180; break; } texture = TextureRotate.RotateImage(texture, angle); Sprite picture = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero, 1); PictureLoaded(true, path, picture); } }
/// <summary> /// Resizes/scales the image data to the specified size and quality /// Refer: http://www.mindscapehq.com/blog/index.php/2012/02/28/windows-phone-7-working-with-camera-tasks/ /// </summary> /// <param name="stream">Image stream</param> /// <param name="width">Target width of the image</param> /// <param name="height">Target height of the image</param> /// <param name="quality">Target quality of the image</param> /// <returns>Formatted image</returns> private byte[] FormatImage(Stream stream, int width, int height, int quality) { WriteableBitmap target = null; BitmapImage image = null; try { JpegInfo info = ExifReader.ReadJpeg(stream, string.Empty); byte[] data = null; int angle = 0; switch (info.Orientation) { case ExifOrientation.TopLeft: case ExifOrientation.Undefined: angle = 0; break; case ExifOrientation.TopRight: angle = 90; break; case ExifOrientation.BottomRight: angle = 180; break; case ExifOrientation.BottomLeft: angle = 270; break; } if (angle > 0d) { target = RotateStream(stream, angle); } if (target == null) { stream.Seek(0, SeekOrigin.Begin); image = new BitmapImage(); image.SetSource(stream); target = new WriteableBitmap(image); } MemoryStream outStream = new MemoryStream(); target.SaveJpeg(outStream, width, height, (int)((PhoneApplicationPage)Mowbly.ActivePhoneApplicationPage).Orientation, quality); outStream.Seek(0, SeekOrigin.Begin); data = ((MemoryStream)outStream).ToArray(); outStream.Close(); outStream.Dispose(); outStream = null; Logger.Debug("Camera: Formatted image [JPG " + width + "x" + height + ";quality" + quality + "]"); return(data); } catch (Exception e) { throw e; } finally { if (image != null) { image.UriSource = null; image = null; } target = null; //outStream ,image,target are eligible for cleanup GCUtils.DoGC(); } }
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { //MessageBox.Show("NavMode:" + e.NavigationMode.ToString()); //MessageBox.Show("Initiator:" + e.IsNavigationInitiator); //Did we get deep linked to? // Get a dictionary of query string keys and values. IDictionary <string, string> queryStrings = this.NavigationContext.QueryString; if (System.Diagnostics.Debugger.IsAttached) { imageControl.Image = new BitmapImage(new Uri("Images/BigImage.jpg", UriKind.Relative)); } if (queryStrings.ContainsKey("token")) { // Retrieve the picture from the media library using the token passed to the application. MediaLibrary library = new MediaLibrary(); Picture picture = library.GetPictureFromToken(queryStrings["token"]); // Create a WriteableBitmap object and add it to the Image control Source property. Stream s = picture.GetImage(); JpegInfo info = ExifLib.ExifReader.ReadJpeg(s, "magic.jpg"); var _width = info.Width; var _height = info.Height; var _orientation = info.Orientation; var _angle = 0; switch (info.Orientation) { case ExifOrientation.TopLeft: case ExifOrientation.Undefined: _angle = 0; break; case ExifOrientation.TopRight: _angle = 90; break; case ExifOrientation.BottomRight: _angle = 180; break; case ExifOrientation.BottomLeft: _angle = 270; break; } s.Seek(0, SeekOrigin.Begin); //DEBUG //MessageBox.Show("Angle: " + _angle); //Stream resultStream; //if (_angle > 0d) //{ // resultStream = RotateStream(s, _angle); //} //else //{ // resultStream = s; //} BitmapImage bitmap = new BitmapImage(); bitmap.CreateOptions = BitmapCreateOptions.None; bitmap.SetSource(s); this.imageControl.RenderTransformOrigin = new Point(0.5, 0.5); this.imageControl.Angle = _angle; this.imageControl.Image = bitmap; } base.OnNavigatedTo(e); }
public MainPage() { InitializeComponent(); StackLayout stackLayout = new StackLayout(); Button takePhotoBtn = new Button { Text = "Сделать фото" }; Button getPhotoBtn = new Button { Text = "Выбрать фото" }; Label gpsLatitude = new Label { Text = "Широта" }; Label gpsLongitude = new Label { Text = "Долгота" }; var map = new CustomMap { IsShowingUser = true, HeightRequest = 100, WidthRequest = 960, VerticalOptions = LayoutOptions.FillAndExpand }; map.RouteCoordinates.Add(new Position(37.785559, -122.396728)); // map.RouteCoordinates.Add(new Position(37.780624, -122.390541)); // map.RouteCoordinates.Add(new Position(37.777113, -122.394983)); map.RouteCoordinates.Add(new Position(37.776831, -122.394627)); map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(37.79752, -122.40183), Distance.FromMiles(1.0))); stackLayout.Children.Add(map); stackLayout.Children.Add(takePhotoBtn); stackLayout.Children.Add(getPhotoBtn); stackLayout.Children.Add(gpsLatitude); stackLayout.Children.Add(gpsLongitude); this.Content = stackLayout; Image img = new Image(); //*Точки маршрута List <WayPoint> wayPoints = new List <WayPoint>() { }; wayPoints.Add(new WayPoint("", "08.04.2018", "55,750904", "48,748493", "the first point")); //Image img = new Image(); // выбор фото getPhotoBtn.Clicked += async(o, e) => { if (CrossMedia.Current.IsPickPhotoSupported) { MediaFile photoPicked = await CrossMedia.Current.PickPhotoAsync(new PickMediaOptions { SaveMetaData = true }); if (photoPicked != null) { await DisplayAlert("Photo Location", photoPicked.Path, "OK"); using (Stream streamPic = photoPicked.GetStream()) { JpegInfo picMetadata = ExifReader.ReadJpeg(streamPic); double[] latitudeComponents = picMetadata.GpsLatitude; double[] longitudeComponents = picMetadata.GpsLongitude; gpsLatitude.Text = latitudeComponents[0].ToString() + latitudeComponents[1] / 60 + latitudeComponents[2] / 3600; gpsLongitude.Text = longitudeComponents[0].ToString() + longitudeComponents[1] / 60 + longitudeComponents[2] / 3600; WayPoint openedPhotoWP = new WayPoint(); openedPhotoWP.DateOfCreation = picMetadata.DateTimeOriginal; openedPhotoWP.GpsLatitude = gpsLatitude.Text; openedPhotoWP.GpsLongitude = gpsLongitude.Text; openedPhotoWP.PicturePath = photoPicked.Path; openedPhotoWP.Comment = picMetadata.Description; wayPoints.Add(openedPhotoWP); } } } }; takePhotoBtn.Clicked += async(o, e) => { await CrossMedia.Current.Initialize(); if (CrossMedia.Current.IsCameraAvailable && CrossMedia.Current.IsTakePhotoSupported) { MediaFile file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions { DefaultCamera = CameraDevice.Rear, SaveToAlbum = true, //Directory = "android/data/com.android.providers.media", Name = $"{DateTime.Now.ToString("dd.MM.yyyy_hh.mm.ss")}.jpg", SaveMetaData = true }); //Intent intent = new Intent(MediaStore.ActionImageCapture); //App._file = new File(App._dir, String.Format("myPhoto_{0}.jpg", Guid.NewGuid())); //intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(App._file)); //StartActivityForResult(intent, 0); if (file == null) { using (Stream streamPic = file.GetStream()) { var picInfo = ExifReader.ReadJpeg(streamPic); gpsLatitude.Text = picInfo.GpsLatitude[0].ToString(); gpsLongitude.Text = picInfo.GpsLongitude[0].ToString(); } return; } img.Source = ImageSource.FromFile(file.Path); } }; }
private void cameraCaptureTask_Completed(object sender, PhotoResult e) { // if no picture was taken if (e.ChosenPhoto == null) { return; } // collect location data watcher.Start(); tookPhoto = true; bool land = false; // figure out the orientation from EXIF data e.ChosenPhoto.Position = 0; JpegInfo info = ExifReader.ReadJpeg(e.ChosenPhoto, e.OriginalFileName); int _width = info.Width; int _height = info.Height; var _orientation = info.Orientation; int _angle = 0; switch (info.Orientation) { case ExifOrientation.TopLeft: case ExifOrientation.Undefined: _angle = 0; land = true; break; case ExifOrientation.TopRight: _angle = 90; break; case ExifOrientation.BottomRight: _angle = 180; land = true; break; case ExifOrientation.BottomLeft: _angle = 270; break; } if (_angle > 0d) { bmp.SetSource(RotateStream(e.ChosenPhoto, _angle)); } else { bmp.SetSource(e.ChosenPhoto); } captured.Source = bmp; // wait til UI thread is done, then navigate Dispatcher.BeginInvoke(() => { if (land) { NavigationService.Navigate(new Uri("/CropPageLandscapeOrientation.xaml", UriKind.Relative)); } else { NavigationService.Navigate(new Uri("/CropPage.xaml", UriKind.Relative)); } }); }