private void SaveDrawing() { if (Control.appearance.ToLower() == "annotate" || Control.appearance.ToLower() == "textannotate") { Bitmap Background = ((BitmapDrawable)BackgroundImage.Drawable).Bitmap; Bitmap CombinedBitmap = OverlayCanvas(Background, dv.bm); using (var os = new FileStream(path, FileMode.Create)) { CombinedBitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, os); } //save any note that the user entered ExifInterface exifData = new ExifInterface(path); exifData.SetAttribute(ExifInterface.TagImageDescription, EditExif.Text); exifData.SaveAttributes(); } else { using (var os = new FileStream(path, FileMode.Create)) { dv.bm.Compress(Bitmap.CompressFormat.Jpeg, 100, os); } } XForm.SetValue(Binding.nodeset, path); Finish(); }
public void GetExifMetadata(string fileName, string OrderId) { ExifInterface exif = new ExifInterface(fileName); string exifMake = exif.GetAttribute(ExifInterface.TagMake); string exifModel = exif.GetAttribute(ExifInterface.TagModel); if (string.IsNullOrEmpty(exifMake)) { exifMake = string.Empty; } if (string.IsNullOrEmpty(exifModel)) { exifModel = string.Empty; } exifMake = exifMake + " " + exifModel; string exifExtraData = GetLocationForExif(exif); string tmp = GetPhoneInformation(); string exifUserData = tmp + "BatchID=" + OrderId + ","; exifModel = exifUserData + exifExtraData; exif.SetAttribute(ExifInterface.TagMake, exifModel); exif.SetAttribute(ExifInterface.TagModel, exifModel); exif.SetAttribute(ExifInterface.TagImageDescription, exifModel); exif.SaveAttributes(); //ReadExifMetadata(fileName); }
public static void LocationToEXIF(string filePath, global::Android.Locations.Location loc) { try { ExifInterface ef = new ExifInterface(filePath); ef.SetAttribute(ExifInterface.TagGpsLatitude, Helpers.DecToDMS(loc.Latitude)); ef.SetAttribute(ExifInterface.TagGpsLongitude, Helpers.DecToDMS(loc.Longitude)); if (loc.Latitude > 0) { ef.SetAttribute(ExifInterface.TagGpsLatitudeRef, "N"); } else { ef.SetAttribute(ExifInterface.TagGpsLatitudeRef, "S"); } if (loc.Longitude > 0) { ef.SetAttribute(ExifInterface.TagGpsLongitudeRef, "E"); } else { ef.SetAttribute(ExifInterface.TagGpsLongitudeRef, "W"); } ef.SaveAttributes(); } catch (System.Exception e) { Console.WriteLine(e.Message); } }
// シャッターを切った時のコールバック public void OnPictureTaken(byte[] data, AndroidCamera camera) { try { var SaveDir = new Java.IO.File(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDcim), "Camera"); if (!SaveDir.Exists()) { SaveDir.Mkdir(); } // 非同期で画像の回転・保存・アルバムへの登録 Task.Run(async() => { // 保存ディレクトリに入ってるファイル数をカウント var Files = SaveDir.List(); int count = 0; foreach (var tmp in Files) { count++; } Matrix matrix = new Matrix(); // 回転用の行列 matrix.SetRotate(90 - DetectScreenOrientation()); Bitmap original = BitmapFactory.DecodeByteArray(data, 0, data.Length); Bitmap rotated = Bitmap.CreateBitmap(original, 0, 0, original.Width, original.Height, matrix, true); var FileName = new Java.IO.File(SaveDir, "DCIM_" + (count + 1) + ".jpg"); // ファイルをストレージに保存 FileStream stream = new FileStream(FileName.ToString(), FileMode.CreateNew); await rotated.CompressAsync(Bitmap.CompressFormat.Jpeg, 90, stream); stream.Close(); Android.Media.ExifInterface Exif = new ExifInterface(FileName.ToString()); Exif.SetAttribute(ExifInterface.TagGpsLatitude, Latitude); Exif.SetAttribute(ExifInterface.TagGpsLongitude, Longitude); Exif.SetAttribute(ExifInterface.TagGpsLatitudeRef, "N"); Exif.SetAttribute(ExifInterface.TagGpsLongitudeRef, "E"); Exif.SaveAttributes(); // 保存したファイルをアルバムに登録 string[] FilePath = { Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDcim) + "/Camera/" + "DCIM_" + (count + 1) + ".jpg" }; string[] mimeType = { "image/jpeg" }; MediaScannerConnection.ScanFile(ApplicationContext, FilePath, mimeType, null); RunOnUiThread(() => { Toast.MakeText(ApplicationContext, "保存しました\n" + FileName, ToastLength.Short).Show(); }); original.Recycle(); rotated.Recycle(); isTakeEnabled = false; }); m_Camera.StartPreview(); } catch (Exception e) { Console.WriteLine(e.Message); } }
public void AddExifData(string filename) { using var exif = new ExifInterface(filename); exif.SetAttribute(ExifInterface.TagXmp, Xmp); exif.SetAttribute(ExifInterface.TagSoftware, "Sketch 360"); exif.SaveAttributes(); }
public static void WriteLocation(this ExifInterface exif, Location location) { exif.SetAttribute(ExifInterface.TagGpsLatitude, GPS.Convert(location.Latitude)); exif.SetAttribute(ExifInterface.TagGpsLatitudeRef, GPS.LatitudeRef(location.Latitude)); exif.SetAttribute(ExifInterface.TagGpsLongitude, GPS.Convert(location.Longitude)); exif.SetAttribute(ExifInterface.TagGpsLongitudeRef, GPS.LongitudeRef(location.Longitude)); exif.SetAttribute(ExifInterface.TagDatetime, ExifFormat.Format(new Date(location.Time))); exif.SaveAttributes(); }
public static ExifInterface SetupNewExif(Dictionary <string, string> exifDict, string path) { ExifInterface newExif = new ExifInterface(path); foreach (var item in exifDict) { newExif.SetAttribute(item.Key, item.Value); } newExif.SaveAttributes(); return(newExif); }
protected override bool[] RunInBackground(string[] urls) { string[] val; bool[] result = new bool[urls.Length + 1]; string[] fileftp = new string[3]; string[] filelocal = new string[3]; DirectoryByFTP(MainActivity.passwd, MainActivity.username, MainActivity.ftppath + "" + App.MyName); val = ListingByFTP(MainActivity.passwd, MainActivity.username, MainActivity.ftppath + "" + App.MyName); if ((val[0] == "The remote server returned an error: (500) 500 NLST: Connection timed out\r\n.") || (val[0] == "Other error")) { Toast.MakeText(FattyFood.MainActivity.myActivity, "Connection timed out ", ToastLength.Long).Show(); result[0] = false; return(result); } foreach (string url in urls) { if (!string.IsNullOrEmpty(url)) { result[Array.IndexOf(urls, url)] = false; filelocal = System.IO.Path.GetFileName(url).Split("."); if (!(val[0] == string.Empty)) { foreach (string v in val) { fileftp = v.Split("."); if ((!(fileftp[1] == "jpg")) && (filelocal[0] == fileftp[0]) && (!(filelocal[1] == fileftp[1]))) { RenameFile(url, fileftp[1]); result[Array.IndexOf(urls, url)] = true; } } } if (result[Array.IndexOf(urls, url)] == false) { using (ExifInterface newexif = new ExifInterface(url)) { string tag = newexif.GetAttribute(ExifInterface.TagUserComment); if (!(tag == "Uped")) { result[Array.IndexOf(urls, url)] = SendFilesByFTP(MainActivity.passwd, MainActivity.username, url, MainActivity.ftppath + App.MyName + "/" + System.IO.Path.GetFileName(url)); } if (result[Array.IndexOf(urls, url)] == true) { newexif.SetAttribute(ExifInterface.TagUserComment, "Uped"); newexif.SaveAttributes(); } } } } } return(result); }
private async Task GeoTagPhotoAsync() { // see if the photo already contains geo coords var exif = new ExifInterface(_file.Path); if (!string.IsNullOrWhiteSpace(exif.GetAttribute(ExifInterface.TagGpsLatitude))) { return; } RequestCurrentLocation(); var location = await _locationTCS.Task; try { int num1Lat = (int)Math.Floor(location.Latitude); int num2Lat = (int)Math.Floor((location.Latitude - num1Lat) * 60); double num3Lat = (location.Latitude - ((double)num1Lat + ((double)num2Lat / 60))) * 3600000; int num1Lon = (int)Math.Floor(location.Longitude); int num2Lon = (int)Math.Floor((location.Longitude - num1Lon) * 60); double num3Lon = (location.Longitude - ((double)num1Lon + ((double)num2Lon / 60))) * 3600000; exif.SetAttribute(ExifInterface.TagGpsLatitude, num1Lat + "/1," + num2Lat + "/1," + num3Lat + "/1000"); exif.SetAttribute(ExifInterface.TagGpsLongitude, num1Lon + "/1," + num2Lon + "/1," + num3Lon + "/1000"); if (location.Latitude > 0) { exif.SetAttribute(ExifInterface.TagGpsLatitudeRef, "N"); } else { exif.SetAttribute(ExifInterface.TagGpsLatitudeRef, "S"); } if (location.Longitude > 0) { exif.SetAttribute(ExifInterface.TagGpsLongitudeRef, "E"); } else { exif.SetAttribute(ExifInterface.TagGpsLongitudeRef, "W"); } exif.SaveAttributes(); } catch (Java.IO.IOException) { // location will not be available on this image, but continue } }
private async Task <List <MediaFile> > HandleMediaFiles(List <MediaFile> mediaList, PickMediaOptions options = null) { if (mediaList == null) { return(null); } if (options == null) { options = new PickMediaOptions(); } //check to see if we picked a file, and if so then try to fix orientation and resize for (int i = 0; i < mediaList.Count; i++) { var media = mediaList[i]; if (string.IsNullOrWhiteSpace(media?.Path) || media?.Type == Abstractions.MediaType.Video) { continue; } try { bool imageChanged = false; var originalMetadata = new ExifInterface(media.Path); if (options.RotateImage) { imageChanged = await FixOrientationAndResizeAsync(media.Path, options, originalMetadata); } else { imageChanged = await ResizeAsync(media.Path, options.PhotoSize, options.CompressionQuality, options.CustomPhotoSize, options.MaxWidthHeight, originalMetadata); } if (imageChanged) { var newExif = new ExifInterface(media.Path); newExif.Copy(originalMetadata); newExif.SaveAttributes(); } else { originalMetadata.SaveAttributes(); } UpdateMetadata(ref media, originalMetadata); } catch (Exception ex) { Console.WriteLine("Unable to check orientation: " + ex); } } return(mediaList); }
/// <summary> /// Picks a photo from the default gallery /// </summary> /// <returns>Media file or null if canceled</returns> public async Task <MediaFile> PickPhotoAsync(PickMediaOptions options = null) { if (!(await RequestStoragePermission())) { throw new MediaPermissionException(Permission.Storage); } var media = await TakeMediaAsync("image/*", Intent.ActionPick, null); if (options == null) { options = new PickMediaOptions(); } //check to see if we picked a file, and if so then try to fix orientation and resize if (!string.IsNullOrWhiteSpace(media?.Path)) { try { var originalMetadata = new ExifInterface(media.Path); if (options.RotateImage) { await FixOrientationAndResizeAsync(media.Path, options, originalMetadata); } else { await ResizeAsync(media.Path, options.PhotoSize, options.CompressionQuality, options.CustomPhotoSize, originalMetadata); } if (options.SaveMetaData && IsValidExif(originalMetadata)) { try { originalMetadata?.SaveAttributes(); } catch (Exception ex) { Console.WriteLine($"Unable to save exif {ex}"); } } originalMetadata?.Dispose(); } catch (Exception ex) { Console.WriteLine("Unable to check orientation: " + ex); } } return(media); }
private void OpenPhoto_Click(object sender, EventArgs e) { ExifInterface newexif; //???????? string tag; foreach (Photo url in mPhotoAlbum) { using (newexif = new ExifInterface(url.mCaption)) { tag = newexif.GetAttribute(ExifInterface.TagUserComment); newexif.SetAttribute(ExifInterface.TagUserComment, ""); newexif.SaveAttributes(); } } }
public void OnPictureTaken(byte[] data, Android.Hardware.Camera camera) { try { System.IO.FileStream fos = new System.IO.FileStream(_filePath, System.IO.FileMode.Create); fos.Write(data, 0, data.Length); fos.Flush(); fos.Close(); ExifInterface exif = new ExifInterface(_filePath); if (exif != null) { int exifroation = 1; switch (_rotation) { case 90: exifroation = 6; break; case 180: exifroation = 3; break; case 270: exifroation = 8; break; default: exifroation = 1; break; } exif.SetAttribute(ExifInterface.TagOrientation, Convert.ToString(exifroation)); exif.SaveAttributes(); int orientation = Convert.ToInt16(exif.GetAttributeInt(ExifInterface.TagOrientation, (int)0)); System.Diagnostics.Debug.WriteLine(orientation); } OnPictureTakenCompleted(EventArgs.Empty); } catch (FileNotFoundException ex) { string message = ex.Message; //Log.Debug(TAG, "File not found: " + ex.getMessage()); } catch (IOException ex) { string message = ex.Message; //Log.Debug(Tag, "Error accessing file: " + ex.getMessage()); } }
void SetExifData(string filePath, Orientation orientation) { try { using (var ei = new ExifInterface(filePath)) { ei.SetAttribute(ExifInterface.TagOrientation, Java.Lang.Integer.ToString((int)orientation)); ei.SaveAttributes(); } } catch (Exception ex) { #if DEBUG throw ex; #endif } }
public static Task <string> ResizeAndCompressImage(string filePath, int maxDimention, int quality) { ExifInterface exifInterface = new ExifInterface(filePath); string [] values = new string[tags.Length]; for (int i = 0; i < tags.Length; i++) { values [i] = exifInterface.GetAttribute(tags [i]); } var task = Task.Run <string>(() => { var extPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath; var filePathOut = System.IO.Path.Combine(extPath, "g4m", "thumb", Guid.NewGuid().ToString()); var dirPath = System.IO.Path.GetDirectoryName(filePathOut); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } //File.Copy(filePath, filePathOut); var fManager = new FileSaveLoad(); Bitmap bmp = LoadAndResizeBitmap(filePath, maxDimention, maxDimention); bmp = GetPictureWithRotation(bmp, exifInterface); var tStream = fManager.OpenFile(filePathOut); bmp.Compress(Bitmap.CompressFormat.Jpeg, quality, tStream); tStream.Flush(); tStream.Close(); ExifInterface innerExif = new ExifInterface(filePathOut); for (int i = 0; i < tags.Length; i++) { if (!string.IsNullOrEmpty(values[i])) { innerExif.SetAttribute(tags[i], values[i]); } } innerExif.SaveAttributes(); return(filePathOut); }); return(task); }
public static void CopyExif(ExifInterface source, ExifInterface destination, Dictionary <string, string> replace) { var build = (int)Build.VERSION.SdkInt; var fields = typeof(ExifInterface).GetFields(); foreach (var field in fields) { var atr = field.GetCustomAttribute <Android.Runtime.RegisterAttribute>(); if (build >= atr?.ApiSince) { var name = (string)field.GetValue(null); var aBuf = replace != null && replace.ContainsKey(name) ? replace[name] : source.GetAttribute(name); if (!string.IsNullOrEmpty(aBuf)) { destination.SetAttribute(name, aBuf); } } } destination.SaveAttributes(); }
private void CaptureImage(byte[] bytes) { var path = System.IO.Path.Combine( Android.App.Application.Context.GetExternalFilesDir(null).AbsolutePath, $"photo_{Guid.NewGuid().ToString()}.jpg"); using (var mFile = new Java.IO.File(path)) { using (var output = new FileOutputStream(mFile)) { try { output.Write(bytes); } catch (Java.IO.IOException e) { e.PrintStackTrace(); } finally { owner.OnCaptureComplete(path); } } } try { var orientation = GetExifOrientation(owner.GetOrientation()); var exif = new ExifInterface(path); exif.SetAttribute( ExifInterface.TagOrientation, Java.Lang.Integer.ToString((int)orientation)); exif.SaveAttributes(); } catch { } }
private async void CameraButton_Clicked(object sender, EventArgs e)//the event handler will be your menu { var photo = await Plugin.Media.CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions() { }); var path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);//having problem to store in a path if (photo != null) { PhotoImage.Source = ImageSource.FromStream(() => { return(photo.GetStream()); }); } ExifInterface newExif = new ExifInterface(path); newExif.SetAttribute(ExifInterface.TagGpsLatitude, "teste lat"); newExif.SetAttribute(ExifInterface.TagGpsLatitudeRef, "teste lat ref"); newExif.SetAttribute(ExifInterface.TagGpsLongitude, "teste long"); newExif.SetAttribute(ExifInterface.TagGpsLongitudeRef, "teste long ref"); newExif.SetAttribute(ExifInterface.TagGpsDatestamp, "GPSDatestamp"); newExif.SetAttribute(ExifInterface.TagDatetime, "Date Time"); newExif.SaveAttributes(); }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { App.bitmap = null; base.OnActivityResult(requestCode, resultCode, data); if (resultCode == Result.Ok) { switch (requestCode) { case REQUEST_EXTERNAL_STORAGE_WRITE: break; case REQUEST_CAMERA: Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile); Uri contentUri = Uri.FromFile(App._file); mediaScanIntent.SetData(contentUri); SendBroadcast(mediaScanIntent); int height = Resources.DisplayMetrics.HeightPixels; int width = Resources.DisplayMetrics.WidthPixels; ExifInterface newexif2 = new ExifInterface(App._file.Path); newexif2.SetAttribute(ExifInterface.TagArtist, App.MyName); newexif2.SaveAttributes(); App.bitmap = App._file.Path.LoadAndResizeBitmap(width, height); GC.Collect(); mPhotoAlbum.SetPhotoAlbum(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures) + "/CameraAppDemo"); break; case SEND_FILE_STATE: // imageView1 = FindViewById<ImageView> (Resource.Id.imageView1); // imageView1.SetImageURI (data.Data); // SendFilesByFTP ("Qq123321@", "foodphoto", GetRealPathFromURI (data.Data), "ftp://files.000webhost.com/public_html/" + System.IO.Path.GetFileName (GetRealPathFromURI (data.Data))); break; default: break; } } }
private static void CopyAttributes(Context context, string sourcePath, string destPath, int reqWidth, int reqHeight) { ExifInterface oldexif = new ExifInterface(sourcePath); ExifInterface newexif = new ExifInterface(destPath); int build = (int)Build.VERSION.SdkInt; if (oldexif.GetAttribute("FNumber") != null) { newexif.SetAttribute("FNumber", oldexif.GetAttribute("FNumber")); } if (oldexif.GetAttribute("ExposureTime") != null) { newexif.SetAttribute("ExposureTime", oldexif.GetAttribute("ExposureTime")); } if (oldexif.GetAttribute("ISOSpeedRatings") != null) { newexif.SetAttribute("ISOSpeedRatings", oldexif.GetAttribute("ISOSpeedRatings")); } if (oldexif.GetAttribute("DateTime") != null) { newexif.SetAttribute("DateTime", oldexif.GetAttribute("DateTime")); } if (oldexif.GetAttribute("Flash") != null) { newexif.SetAttribute("Flash", oldexif.GetAttribute("Flash")); } if (oldexif.GetAttribute("GPSLatitude") != null) { newexif.SetAttribute("GPSLatitude", oldexif.GetAttribute("GPSLatitude")); } if (oldexif.GetAttribute("GPSLatitudeRef") != null) { newexif.SetAttribute("GPSLatitudeRef", oldexif.GetAttribute("GPSLatitudeRef")); } if (oldexif.GetAttribute("GPSLongitude") != null) { newexif.SetAttribute("GPSLongitude", oldexif.GetAttribute("GPSLongitude")); } if (oldexif.GetAttribute("GPSLatitudeRef") != null) { newexif.SetAttribute("GPSLongitudeRef", oldexif.GetAttribute("GPSLongitudeRef")); } //Need to update it, with your new height width newexif.SetAttribute("ImageLength", reqHeight.ToString()); newexif.SetAttribute("ImageWidth", reqWidth.ToString()); if (oldexif.GetAttribute("Make") != null) { newexif.SetAttribute("Make", oldexif.GetAttribute("Make")); } if (oldexif.GetAttribute("Model") != null) { newexif.SetAttribute("Model", oldexif.GetAttribute("Model")); } if (oldexif.GetAttribute("Orientation") != null) { newexif.SetAttribute("Orientation", oldexif.GetAttribute("Orientation")); } if (oldexif.GetAttribute("WhiteBalance") != null) { newexif.SetAttribute("WhiteBalance", oldexif.GetAttribute("WhiteBalance")); } newexif.SaveAttributes(); Android.Provider.MediaStore.Images.Media.InsertImage(context.ContentResolver, destPath, "", ""); }
public byte[] ResizeImageAndroid(string FileDesc, byte[] imageData, float width, float height) { ExifInterface oldExif = new ExifInterface(FileDesc); String exifOrientation = oldExif.GetAttribute(ExifInterface.TagOrientation); // Load the bitmap Bitmap originalImage = BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length); // float ZielHoehe = 0; float ZielBreite = 0; // var Hoehe = originalImage.Height; var Breite = originalImage.Width; // float NereyeRotate = 0; if (Hoehe > Breite) // Höhe (71 für Avatar) ist Master { ZielHoehe = height; float teiler = Hoehe / height; ZielBreite = Breite / teiler; NereyeRotate = 0; } else if (Hoehe < Breite) // Breite (61 für Avatar) ist Master { ZielBreite = width; float teiler = Breite / width; ZielHoehe = Hoehe / teiler; NereyeRotate = -90; } else //EsitOlmaDurumu { ZielBreite = width; ZielHoehe = height; NereyeRotate = 0; } // Bitmap resizedImage = Bitmap.CreateScaledBitmap(originalImage, (int)ZielBreite, (int)ZielHoehe, true); //return rotateBitmap(resizedImage, 0); using (MemoryStream ms = new MemoryStream()) { resizedImage.Compress(Bitmap.CompressFormat.Jpeg, 100, ms); var Guidee = Guid.NewGuid().ToString(); var FilePath = System.IO.Path.Combine(documentsFolder(), Guidee + ".jpg"); System.IO.File.WriteAllBytes(FilePath, ms.ToArray()); if (System.IO.File.Exists(FilePath)) { if (exifOrientation != null) { ExifInterface newExif = new ExifInterface(FilePath); newExif.SetAttribute(ExifInterface.TagOrientation, exifOrientation); newExif.SaveAttributes(); var bytess = System.IO.File.ReadAllBytes(FilePath); System.IO.File.Delete(FileDesc); System.IO.File.Delete(FilePath); return(bytess); } else { return(null); } } else { return(null); } } }
/// <summary> /// Take a photo async with specified options /// </summary> /// <param name="options">Camera Media Options</param> /// <returns>Media file of photo or null if canceled</returns> public async Task <MediaFile> TakePhotoAsync(StoreCameraMediaOptions options) { if (!IsCameraAvailable) { throw new NotSupportedException(); } if (!(await RequestCameraPermissions())) { throw new MediaPermissionException(Permission.Camera); } VerifyOptions(options); var media = await TakeMediaAsync("image/*", MediaStore.ActionImageCapture, options); if (string.IsNullOrWhiteSpace(media?.Path)) { return(media); } if (options.SaveToAlbum) { try { var fileName = System.IO.Path.GetFileName(media.Path); var publicUri = MediaPickerActivity.GetOutputMediaFile(context, options.Directory ?? "temp", fileName, true, true); using (System.IO.Stream input = File.OpenRead(media.Path)) using (System.IO.Stream output = File.Create(publicUri.Path)) input.CopyTo(output); media.AlbumPath = publicUri.Path; var f = new Java.IO.File(publicUri.Path); //MediaStore.Images.Media.InsertImage(context.ContentResolver, // f.AbsolutePath, f.Name, null); try { Android.Media.MediaScannerConnection.ScanFile(context, new[] { f.AbsolutePath }, null, context as MediaPickerActivity); ContentValues values = new ContentValues(); values.Put(MediaStore.Images.Media.InterfaceConsts.Title, System.IO.Path.GetFileNameWithoutExtension(f.AbsolutePath)); values.Put(MediaStore.Images.Media.InterfaceConsts.Description, string.Empty); values.Put(MediaStore.Images.Media.InterfaceConsts.DateTaken, Java.Lang.JavaSystem.CurrentTimeMillis()); values.Put(MediaStore.Images.ImageColumns.BucketId, f.ToString().ToLowerInvariant().GetHashCode()); values.Put(MediaStore.Images.ImageColumns.BucketDisplayName, f.Name.ToLowerInvariant()); values.Put("_data", f.AbsolutePath); var cr = context.ContentResolver; cr.Insert(MediaStore.Images.Media.ExternalContentUri, values); } catch (Exception ex1) { Console.WriteLine("Unable to save to scan file: " + ex1); } var contentUri = Android.Net.Uri.FromFile(f); var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile, contentUri); context.SendBroadcast(mediaScanIntent); } catch (Exception ex2) { Console.WriteLine("Unable to save to gallery: " + ex2); } } //check to see if we need to rotate if success try { var exif = new ExifInterface(media.Path); if (options.RotateImage) { await FixOrientationAndResizeAsync(media.Path, options, exif); } else { await ResizeAsync(media.Path, options.PhotoSize, options.CompressionQuality, options.CustomPhotoSize, exif); } if (options.SaveMetaData && IsValidExif(exif)) { SetMissingMetadata(exif, options.Location); try { exif?.SaveAttributes(); } catch (Exception ex) { Console.WriteLine($"Unable to save exif {ex}"); } } exif?.Dispose(); } catch (Exception ex) { Console.WriteLine("Unable to check orientation: " + ex); } return(media); }
/// <summary> /// Take a photo async with specified options /// </summary> /// <param name="options">Camera Media Options</param> /// <param name="token">Cancellation token</param> /// <returns>Media file of photo or null if canceled</returns> public async Task <MediaFile> TakePhotoAsync(StoreCameraMediaOptions options, CancellationToken token = default(CancellationToken)) { if (!IsCameraAvailable) { throw new NotSupportedException(); } if (!(await RequestCameraPermissions())) { throw new MediaPermissionException(nameof(Permissions.Camera)); } VerifyOptions(options); var media = await TakeMediaAsync("image/*", MediaStore.ActionImageCapture, options, token); if (string.IsNullOrWhiteSpace(media?.Path)) { return(media); } if (options.SaveToAlbum) { var fileName = System.IO.Path.GetFileName(media.Path); var uri = MediaPickerActivity.GetOutputMediaFile(context, options.Directory ?? "temp", fileName, true, true); var f = new Java.IO.File(uri.Path); media.AlbumPath = uri.ToString(); try { var values = new ContentValues(); values.Put(MediaStore.Audio.Media.InterfaceConsts.DisplayName, System.IO.Path.GetFileNameWithoutExtension(f.AbsolutePath)); values.Put(MediaStore.Audio.Media.InterfaceConsts.MimeType, "image/jpeg"); values.Put(MediaStore.Images.Media.InterfaceConsts.Description, string.Empty); values.Put(MediaStore.Images.Media.InterfaceConsts.DateTaken, Java.Lang.JavaSystem.CurrentTimeMillis()); values.Put(MediaStore.Images.ImageColumns.BucketId, f.ToString().ToLowerInvariant().GetHashCode()); values.Put(MediaStore.Images.ImageColumns.BucketDisplayName, f.Name.ToLowerInvariant()); var cr = context.ContentResolver; var albumUri = cr.Insert(MediaStore.Images.Media.ExternalContentUri, values); using (System.IO.Stream input = File.OpenRead(media.Path)) using (System.IO.Stream output = cr.OpenOutputStream(albumUri)) input.CopyTo(output); } catch (Exception ex) { Console.WriteLine("Unable to save to gallery: " + ex); } } //check to see if we need to rotate if success try { var exif = new ExifInterface(media.Path); if (options.RotateImage) { await FixOrientationAndResizeAsync(media.Path, options, exif); } else { await ResizeAsync(media.Path, options, exif); } if (options.SaveMetaData && IsValidExif(exif)) { SetMissingMetadata(exif, options.Location); try { exif?.SaveAttributes(); } catch (Exception ex) { Console.WriteLine($"Unable to save exif {ex}"); } } exif?.Dispose(); } catch (Exception ex) { Console.WriteLine("Unable to check orientation: " + ex); } return(media); }
/// <summary> /// Take a photo async with specified options /// </summary> /// <param name="options">Camera Media Options</param> /// <returns>Media file of photo or null if canceled</returns> public async Task <MediaFile> TakePhotoAsync(StoreCameraMediaOptions options) { if (!IsCameraAvailable) { throw new NotSupportedException(); } if (!(await RequestCameraPermissions())) { return(null); } VerifyOptions(options); var mediaList = (await TakeMediaAsync("image/*", MediaStore.ActionImageCapture, options)); if (mediaList == null) { return(null); } var media = mediaList.First(); if (string.IsNullOrWhiteSpace(media?.Path)) { return(media); } //check to see if we need to rotate if success try { bool imageChanged = false; var exif = new ExifInterface(media.Path); exif.SetAttribute(ExifInterface.TagDatetime, DateTime.Now.ToString("yyyy:MM:dd HH:mm:ss")); exif.SetAttribute(ExifInterface.TagDatetimeOriginal, DateTime.Now.ToString("yyyy:MM:dd HH:mm:ss")); if (options.RotateImage) { imageChanged = await FixOrientationAndResizeAsync(media.Path, options, exif); } else { imageChanged = await ResizeAsync(media.Path, options.PhotoSize, options.CompressionQuality, options.CustomPhotoSize, options.MaxWidthHeight, exif); } SetMissingMetadata(exif, options.Location); if (imageChanged) { var newExif = new ExifInterface(media.Path); newExif.Copy(exif); newExif.SaveAttributes(); } else { exif.SaveAttributes(); } UpdateMetadata(ref media, exif); if (options.SaveToAlbum) { SaveMediaToAlbum(options, media); } } catch (Exception ex) { Console.WriteLine("Unable to check orientation: " + ex); } return(media); }