private void ReadExifMetadata(string fileName) { ExifInterface exif = new ExifInterface(fileName); string model = exif.GetAttribute(ExifInterface.TagModel); string desc = exif.GetAttribute(ExifInterface.TagImageDescription); string make = exif.GetAttribute(ExifInterface.TagMake); }
void SetMissingMetadata(ExifInterface exif, Location location) { if (exif == null) { return; } var position = new float[6]; if (!exif.GetLatLong(position) && location != null) { exif.SetAttribute(ExifInterface.TagGpsLatitude, CoordinateToRational(location.Latitude)); exif.SetAttribute(ExifInterface.TagGpsLongitude, CoordinateToRational(location.Longitude)); exif.SetAttribute(ExifInterface.TagGpsLatitudeRef, location.Latitude > 0 ? "N" : "S"); exif.SetAttribute(ExifInterface.TagGpsLongitudeRef, location.Longitude > 0 ? "E" : "W"); } if (string.IsNullOrEmpty(exif.GetAttribute(ExifInterface.TagDatetime))) { exif.SetAttribute(ExifInterface.TagDatetime, DateTime.Now.ToString("yyyy:MM:dd hh:mm:ss")); } if (string.IsNullOrEmpty(exif.GetAttribute(ExifInterface.TagMake))) { exif.SetAttribute(ExifInterface.TagMake, Build.Manufacturer); } if (string.IsNullOrEmpty(exif.GetAttribute(ExifInterface.TagModel))) { exif.SetAttribute(ExifInterface.TagModel, Build.Model); } }
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 Print(this ExifInterface dest) { foreach (var tagName in tagNames) { if (!string.IsNullOrEmpty(dest.GetAttribute(tagName))) { Debug.WriteLine($"{tagName}: {dest.GetAttribute(tagName)}"); } } }
private Bitmap LoadAndResizeBitmap() { if (Path.StartsWith("http")) { //var webImage = GetImageBitmapFromUrl(Path); //return Bitmap.CreateScaledBitmap(webImage, _screenWidth, _screenHeight, false); return(GetImageBitmapFromUrl(Path)); } // First we get the the dimensions of the file on disk BitmapFactory.Options options = new BitmapFactory.Options { InJustDecodeBounds = true }; BitmapFactory.DecodeFile(Path, options); // Next we calculate the ratio that we need to resize the image by // in order to fit the requested dimensions. int outHeight = options.OutHeight; int outWidth = options.OutWidth; int inSampleSize = 1; if (outHeight > _screenHeight || outWidth > _screenWidth) { inSampleSize = outWidth > outHeight ? outHeight / _screenHeight : outWidth / _screenWidth; } // Now we will load the image and have BitmapFactory resize it for us. options.InSampleSize = inSampleSize; options.InJustDecodeBounds = false; Bitmap resizedBitmap = BitmapFactory.DecodeFile(Path, options); // Images are being saved in landscape, so rotate them back to portrait if they were taken in portrait Matrix mtx = new Matrix(); ExifInterface exif = new ExifInterface(Path); string orientation = exif.GetAttribute(ExifInterface.TagOrientation); switch (orientation) { case "6": // portrait mtx.PreRotate(90); resizedBitmap = Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, mtx, false); mtx.Dispose(); mtx = null; break; case "1": // landscape break; default: mtx.PreRotate(90); resizedBitmap = Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, mtx, false); mtx.Dispose(); mtx = null; break; } return(resizedBitmap); }
public string GetMetadata(ExifInterface exif) { //var wtf = (Android.Media.Orientation)exif.GetAttributeInt(ExifInterface.TagOrientation, (int)Android.Media.Orientation.Normal); var wtf = exif.GetAttribute("ThumbnailImage"); wtf = exif.GetAttribute("DateTime"); wtf = exif.GetAttribute("DateTimeOriginal"); wtf = exif.GetAttribute("DateTimeDigitized"); int debug = 1; return(wtf); }
public static void Copy(this ExifInterface dest, ExifInterface source) { foreach (var tagName in tagNames) { dest.SetAttribute(tagName, source.GetAttribute(tagName)); } }
private async Task Save(byte[] bytes) { using (OutputStream output = new FileOutputStream(File)) { output.Write(bytes); } global::Android.Graphics.Bitmap bitmap = global::Android.Graphics.BitmapFactory.DecodeFile(File.AbsolutePath); ExifInterface exif = new ExifInterface(File.AbsolutePath); string orientation = exif.GetAttribute(ExifInterface.TagOrientation); switch (orientation) { case "6": bitmap = Camera1Fragment.Rotate(bitmap, 90); break; case "8": bitmap = Camera1Fragment.Rotate(bitmap, 270); break; case "3": bitmap = Camera1Fragment.Rotate(bitmap, 180); break; } await AndroidUtils.WriteBitmapToFile(File.AbsolutePath, bitmap); }
/// <summary> /// Rotate the picture taken /// https://forums.xamarin.com/discussion/5409/photo-being-saved-in-landscape-not-portrait /// </summary> /// <param name="path"></param> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> void RotateBitmap(string path, byte[] data) { try { //using (Android.Graphics.Bitmap picture = Android.Graphics.BitmapFactory.DecodeFile(path)) using (Android.Graphics.Bitmap picture = data.ToBitmap()) using (Android.Graphics.Matrix mtx = new Android.Graphics.Matrix()) { ExifInterface exif = new ExifInterface(path); string orientation = exif.GetAttribute(ExifInterface.TagOrientation); var camOrientation = int.Parse(orientation); switch (_imageRotation) { case 0: // landscape break; case 90: // landscape upside down mtx.PreRotate(270); break; case 180: // portrait mtx.PreRotate(180); break; case 270: // portrait upside down mtx.PreRotate(90); break; } var maxSize = 1024; double w = picture.Width; double h = picture.Height; if (picture.Width > maxSize || picture.Height > maxSize) { // set scaled width and height to prevent out of memory exception double scaleFactor = (double)maxSize / (double)picture.Width; if (picture.Height > picture.Width) { scaleFactor = (double)maxSize / picture.Height; } w = picture.Width * scaleFactor; h = picture.Height * scaleFactor; } using (var scaledPiture = Android.Graphics.Bitmap.CreateScaledBitmap(picture, (int)w, (int)h, false)) using (var rotatedPiture = Android.Graphics.Bitmap.CreateBitmap(scaledPiture, 0, 0, (int)w, (int)h, mtx, false)) { SaveFile(path, rotatedPiture.ToBytes()); } } } catch (Java.Lang.OutOfMemoryError e) { e.PrintStackTrace(); throw; } }
public static Bitmap LoadImageAndResize(this Context context, string imagesFolder, string imageFileName, int width, int height) { if (Environment.ExternalStorageState != Environment.MediaMounted) { return(null); } var fileName = GetImagesPath(context, imagesFolder) + File.Separator + imageFileName; BitmapFactory.Options options = new BitmapFactory.Options { InJustDecodeBounds = true }; BitmapFactory.DecodeFile(fileName, options); int outHeight = options.OutHeight; int outWidth = options.OutWidth; int inSampleSize = 1; if (outHeight > height || outWidth > width) { inSampleSize = outWidth > outHeight ? outHeight / height : outWidth / width; } options.InSampleSize = inSampleSize; options.InJustDecodeBounds = false; options.InPreferredConfig = Bitmap.Config.Rgb565; Bitmap bm = BitmapFactory.DecodeFile(fileName, options); Matrix mtx = new Matrix(); ExifInterface exif = new ExifInterface(GetImagesPath(context, imagesFolder) + File.Separator + imageFileName); string orientation = exif.GetAttribute(ExifInterface.TagOrientation); switch (orientation) { case "6": // portrait mtx.PreRotate(90); bm = Bitmap.CreateBitmap(bm, 0, 0, bm.Width, bm.Height, mtx, false); mtx.Dispose(); mtx = null; break; case "1": // landscape break; default: mtx.PreRotate(90); bm = Bitmap.CreateBitmap(bm, 0, 0, bm.Width, bm.Height, mtx, false); mtx.Dispose(); mtx = null; break; } return(bm); }
public static Bitmap LoadandResizeBitmap(this string fileName, int width, int height) { // First get teh dimensions of the file on disk BitmapFactory.Options options = new BitmapFactory.Options { InJustDecodeBounds = true }; BitmapFactory.DecodeFile(fileName, options); // Next calculate the ratio that we need to resize the image by // in order to fit the requested dimensions int outHeight = options.OutHeight; int outWidth = options.OutWidth; int inSampleSize = 1; if (outHeight > height || outWidth > width) { inSampleSize = outWidth > outHeight ? outHeight / height : outWidth / width; } // Now load the image and have BitmapFactory resize it options.InSampleSize = inSampleSize; options.InJustDecodeBounds = false; Bitmap resizedBitmap = BitmapFactory.DecodeFile(fileName, options); // Images are being saved in landscape, so rotate them back to protrait if they // were taken in portrait Matrix mtx = new Matrix(); ExifInterface exif = new ExifInterface(fileName); string orientation = exif.GetAttribute(ExifInterface.TagOrientation); switch (orientation) { case "6": // Portrait mtx.PreRotate(90); resizedBitmap = Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, mtx, false); mtx.Dispose(); mtx = null; break; case "1": // Landscape break; default: mtx.PreRotate(90); resizedBitmap = Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, mtx, false); mtx.Dispose(); mtx = null; break; } return(resizedBitmap); }
//public int CheckRotationByExifInterface(string path) //{ // imageUri = Android.Net.Uri.FromFile(new Java.IO.File(path)); // System.IO.Stream input = Fragment.Context.ContentResolver.OpenInputStream(imageUri); // var exifInterface = new ExifInterface(input); // TryGetLocation(exifInterface); // int orientation = exifInterface.GetAttributeInt(ExifInterface.TagOrientation, ExifInterface.OrientationFlipHorizontal); // return orientation; //} private void TryGetLocation(ExifInterface exifInterface) { try { imageLat = 0; imageLong = 0; var _gps_Latitude = exifInterface.GetAttribute(ExifInterface.TagGpsLatitude); var _gps_Longitude = exifInterface.GetAttribute(ExifInterface.TagGpsLongitude); var _gps_LatitudeRef = exifInterface.GetAttribute(ExifInterface.TagGpsLatitudeRef); var _gps_LongitudeRef = exifInterface.GetAttribute(ExifInterface.TagGpsLongitudeRef); imageLat = PhotoGpsLocationConverter.CheckAndConvert(_gps_Latitude, _gps_LatitudeRef, true); imageLong = PhotoGpsLocationConverter.CheckAndConvert(_gps_Longitude, _gps_LongitudeRef, false); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Can't get image location: " + ex.Message); } }
public string GetPhotoDate(string path) { if (!File.Exists(path)) { return("0"); } ExifInterface exif = new ExifInterface(path); return(exif.GetAttribute(ExifInterface.TagDatetime)); }
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 } }
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); }
void SetMissingMetadata(ExifInterface exif, Location location) { var exifPos = exif.GetLatLong(); if (exifPos == null && location != null && location.Latitude != null && location.Longitude != null) { exif.SetLatLong((double)location.Latitude, (double)location.Longitude); } if (string.IsNullOrEmpty(exif.GetAttribute(ExifInterface.TagDatetime))) { 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 (string.IsNullOrEmpty(exif.GetAttribute(ExifInterface.TagMake))) { exif.SetAttribute(ExifInterface.TagMake, Build.Manufacturer); } if (string.IsNullOrEmpty(exif.GetAttribute(ExifInterface.TagModel))) { exif.SetAttribute(ExifInterface.TagModel, Build.Model); } }
void UpdateMetadata(ref MediaFile media, ExifInterface exif) { var dateString = exif.GetAttribute(ExifInterface.TagDatetime); if (dateString != null) { media.MediaTakenAt = DateTime.ParseExact(dateString, "yyyy:MM:dd HH:mm:ss", CultureInfo.InvariantCulture); } else { media.MediaTakenAt = null; } media.Orientation = exif.GetAttributeInt(ExifInterface.TagOrientation, ExifInterface.OrientationUndefined); var latString = exif.GetAttribute(ExifInterface.TagGpsLatitude); media.Latitude = ParseRational(latString); media.LatitudeRef = exif.GetAttribute(ExifInterface.TagGpsLatitudeRef); var longString = exif.GetAttribute(ExifInterface.TagGpsLongitude); media.Longitude = ParseRational(longString); media.LongitudeRef = exif.GetAttribute(ExifInterface.TagGpsLongitudeRef); }
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 static Bitmap RotateImageIfRequired(Bitmap img, string url) { var ei = new ExifInterface(url); var orientation = ei.GetAttribute(ExifInterface.TagOrientation); if (string.IsNullOrEmpty(orientation) || orientation == "0") { return(img); } var matrix = GetMatrixOrientation(ei, 0); var rotated = Bitmap.CreateBitmap(img, 0, 0, img.Width, img.Height, matrix, true); img.Recycle(); img.Dispose(); return(rotated); }
private static Matrix GetMatrixOrientation(ExifInterface sourceExif, float degrees) { var matrix = new Matrix(); var orientation = sourceExif.GetAttribute(ExifInterface.TagOrientation); switch (orientation) { case "1": //Horizontal(normal) matrix.PostRotate(degrees); break; case "2": //Mirror horizontal matrix.SetScale(-1, 1); matrix.PostRotate(degrees); break; case "3": //Rotate 180 matrix.PostRotate(180 + degrees); break; case "4": //Mirror vertical matrix.PostRotate(180 + degrees); matrix.SetScale(-1, 1); break; case "5": //Mirror horizontal and rotate 270 CW matrix.PostScale(-1, 1); matrix.SetRotate(270 + degrees); break; case "6": //Rotate 90 CW matrix.SetRotate(90 + degrees); break; case "7": //Mirror horizontal and rotate 90 CW matrix.PostScale(-1, 1); matrix.SetRotate(90 + degrees); break; case "8": //Rotate 270 CW matrix.SetRotate(270 + degrees); break; } return(matrix); }
public static Location ReadLocation(this ExifInterface exif) { var pos = new float[2]; if (exif.GetLatLong(pos)) { var date = exif.GetAttribute(ExifInterface.TagDatetime); var time = ExifFormat.Parse(date).Time; return(new Location("exif") { Latitude = pos[0], Longitude = pos[1], Time = time }); } return(null); }
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); }
/// <summary> /// Obtains the EXIF data of the given URI. /// </summary> /// <param name="oldUri">The URI you wish to get the EXIF data</param> /// <param name="context">Your current context (Activity most likely)</param> /// <returns></returns> public static Dictionary <string, string> CopyExif(Android.Net.Uri oldUri, Context context) { //somewhere around here we get the exif data //photofile is the temp image Dictionary <string, string> ExifDict = new Dictionary <string, string>(); var stream = context.ContentResolver.OpenInputStream(oldUri); ExifInterface oldExif = new ExifInterface(stream); foreach (string s in attributes) { string value = oldExif.GetAttribute(s); if (value != null) { ExifDict.Add(s, value); } } return(ExifDict); }
public void OnPictureTaken(byte[] data, Camera camera) { string id = null; if (((CameraActivity)Activity).activityId != -1) { id = ((CameraActivity)Activity).activityId.ToString(); } string filename = Path.Combine( Common.LocalData.Storage.GetCacheFolder(id), DateTime.Now.ToString("MM-dd-yyyy-HH-mm-ss-fff", CultureInfo.InvariantCulture) + ".jpg"); File.WriteAllBytes(filename, data); global::Android.Graphics.Bitmap bitmap = global::Android.Graphics.BitmapFactory.DecodeFile(filename); ExifInterface exif = new ExifInterface(filename); string orientation = exif.GetAttribute(ExifInterface.TagOrientation); switch (orientation) { case "6": bitmap = Rotate(bitmap, 90); break; case "8": bitmap = Rotate(bitmap, 270); break; case "3": bitmap = Rotate(bitmap, 180); break; } var suppress = AndroidUtils.WriteBitmapToFile(filename, bitmap); OnPause(); ((CameraActivity)Activity).ReturnWithFile(filename); }
//Background image public void LoadImage(string path, bool IsInResources, Abstractions.Scaling Scaling = Abstractions.Scaling.Absolute_None) { backgroundScaling = Scaling; if (IsInResources) { string file = path.Split('.')[0]; var id = Resources.GetIdentifier(file.ToLower(), "drawable", Context.PackageName); backgroundBitmap = BitmapFactory.DecodeResource(Resources, id); } else { backgroundBitmap = BitmapFactory.DecodeFile(path); ExifInterface exif = new ExifInterface(path); var orientationAttribute = exif.GetAttribute(ExifInterface.TagOrientation); Android.Media.Orientation orientationRotate = (Android.Media.Orientation) int.Parse(orientationAttribute); int imageRotation = 0; switch (orientationRotate) { case Android.Media.Orientation.Rotate90: imageRotation = 90; break; case Android.Media.Orientation.Rotate180: imageRotation = 180; break; case Android.Media.Orientation.Rotate270: imageRotation = 270; break; } imageSize.X = backgroundBitmap.Width; imageSize.Y = backgroundBitmap.Height; orientation = imageRotation; backgroundBitmap = RotateBitmap(backgroundBitmap, imageRotation); } }
public static Bitmap LoadImage(this Context context, string imagesFolder, string imageFileName, BitmapFactory.Options options = null) { if (Environment.ExternalStorageState != Environment.MediaMounted) { return(null); } if (options != null) { Bitmap bm = BitmapFactory.DecodeFile(GetImagesPath(context, imagesFolder) + File.Separator + imageFileName, options); Matrix mtx = new Matrix(); ExifInterface exif = new ExifInterface(GetImagesPath(context, imagesFolder) + File.Separator + imageFileName); string orientation = exif.GetAttribute(ExifInterface.TagOrientation); switch (orientation) { case "6": // portrait mtx.PreRotate(90); bm = Bitmap.CreateBitmap(bm, 0, 0, bm.Width, bm.Height, mtx, false); mtx.Dispose(); mtx = null; break; case "1": // landscape break; default: mtx.PreRotate(90); bm = Bitmap.CreateBitmap(bm, 0, 0, bm.Width, bm.Height, mtx, false); mtx.Dispose(); mtx = null; break; } return(bm); } return(BitmapFactory.DecodeFile(context.GetImagesPath(imagesFolder) + File.Separator + imageFileName)); }
protected override void OnActivityResult(int requestCode, Android.App.Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); this.RequestedOrientation = Android.Content.PM.ScreenOrientation.Portrait; if (requestCode == 0) { switch (resultCode) { case Android.App.Result.Ok: if (imagefile.Exists()) { //Salvar imagem na galeria Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile); contentUri = Android.Net.Uri.FromFile(imagefile); mediaScanIntent.SetData(contentUri); SendBroadcast(mediaScanIntent); //Converter image para byte Java.Net.URI juri = new Java.Net.URI(contentUri.ToString()); ByteHelper helper = new ByteHelper(); bytes = helper.imageToByteArray(juri, bytes); System.IO.Stream stream = ContentResolver.OpenInputStream(contentUri); imageView.SetImageBitmap(BitmapFactory.DecodeStream(stream)); BitmapFactory.Options options = new BitmapFactory.Options { InJustDecodeBounds = true }; BitmapFactory.DecodeFile(contentUri.ToString(), options); //options.InJustDecodeBounds = false; Matrix mtx = new Matrix(); ExifInterface exif = new ExifInterface(contentUri.ToString()); string orientation = exif.GetAttribute(ExifInterface.TagOrientation); switch (orientation) { case "6": mtx.PreRotate(90); mtx.Dispose(); mtx = null; break; case "1": break; default: mtx.PreRotate(90); mtx.Dispose(); mtx = null; break; } } else { Toast.MakeText(this, "O arquivo não foi salvo devido à um erro", ToastLength.Short).Show(); } break; case Result.FirstUser: string Lat = data.GetStringExtra("Lat"); string Long = data.GetStringExtra("Lon"); string mensagem = data.GetStringExtra("mensagem"); string endereco = data.GetStringExtra("Endereco"); if ((Lat == null || Lat == "") && (Long == null || Long == "")) { Toast.MakeText(this, "Endereço não encontrado. Verifique se seu GPS está ativado e tente novamente", ToastLength.Long).Show(); txtGeolocalizacao.Visibility = ViewStates.Visible; txtGeolocalizacao.Text = ""; checkBoxGeolocalizacao.Checked = false; } else { txtGeolocalizacao.Visibility = ViewStates.Visible; txtGeolocalizacao.Text = Lat + ", " + Long; } break; case Result.Canceled: break; default: break; } } }
Bitmap loadAndResizeBitmap(string filePath) { BitmapFactory.Options options = new BitmapFactory.Options { InJustDecodeBounds = true }; BitmapFactory.DecodeFile(filePath, options); int REQUIRED_SIZE = 100; int width_tmp = options.OutWidth, height_tmp = options.OutHeight; int scale = 4; while (true) { if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) { break; } width_tmp /= 2; height_tmp /= 2; scale++; } options.InSampleSize = scale; options.InJustDecodeBounds = false; Bitmap resizedBitmap = BitmapFactory.DecodeFile(filePath, options); ExifInterface exif = null; try { exif = new ExifInterface(filePath); string orientation = exif.GetAttribute(ExifInterface.TagOrientation); Matrix matrix = new Matrix(); switch (orientation) { case "1": // landscape break; case "3": matrix.PreRotate(180); resizedBitmap = Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, matrix, false); matrix.Dispose(); matrix = null; break; case "4": matrix.PreRotate(180); resizedBitmap = Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, matrix, false); matrix.Dispose(); matrix = null; break; case "5": matrix.PreRotate(90); resizedBitmap = Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, matrix, false); matrix.Dispose(); matrix = null; break; case "6": // portrait matrix.PreRotate(90); resizedBitmap = Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, matrix, false); matrix.Dispose(); matrix = null; break; case "7": matrix.PreRotate(-90); resizedBitmap = Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, matrix, false); matrix.Dispose(); matrix = null; break; case "8": matrix.PreRotate(-90); resizedBitmap = Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, matrix, false); matrix.Dispose(); matrix = null; break; } return(resizedBitmap); } catch (IOException ex) { Console.WriteLine("An exception was thrown when reading exif from media file...:" + ex.Message); return(null); } }
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 SetupDrawingCanvas() { path = XForm.GetValue(Binding.nodeset); if (!string.IsNullOrEmpty(path)) { Bitmap bitmap = BitmapFactory.DecodeFile(path); //grab the exif note if there is one ExifInterface exifData = new ExifInterface(path); string note = exifData.GetAttribute(ExifInterface.TagImageDescription); if (note != null) { EditExif.Text = note; } //grab orientation if there is one, some images from the net may not even have it int orientation = exifData.GetAttributeInt(Android.Media.ExifInterface.TagOrientation, 1); switch (orientation) { case 6: bitmap = BitmapHelpers.RotateBitmap(bitmap, 90f); break; case 3: bitmap = BitmapHelpers.RotateBitmap(bitmap, 180f); break; case 8: bitmap = BitmapHelpers.RotateBitmap(bitmap, 270f); break; } Dims = new int[] { bitmap.Width, bitmap.Height }; //this one liner does all, gets the lower of the two to determine what to scale it by decimal scale = Math.Min(Decimal.Divide(MainCanvas.Width, Dims[0]), Decimal.Divide(MainCanvas.Height, Dims[1])); int width = (int)(Dims[0] * scale); int height = (int)(Dims[1] * scale); //background image if (Control.appearance.ToLower() == "annotate" || Control.appearance.ToLower() == "textannotate") { bitmap = Bitmap.CreateScaledBitmap(bitmap, width, height, true); BackgroundImage.SetImageBitmap(bitmap); } //canvas image if (TempBitmap != null) { canvasBitmap = Bitmap.CreateScaledBitmap(TempBitmap, width, height, true); } else { canvasBitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888); } if (dv == null) { dv = new DrawingView(this, canvasBitmap, 10, BackgroundImage); } if (Control.appearance.ToLower() != "signature") { SetupEvents(); } var layoutParams = new RelativeLayout.LayoutParams(width, height); layoutParams.AddRule(LayoutRules.CenterInParent); dv.LayoutParameters = layoutParams; MainCanvas.AddView(dv); GC.Collect(); } else if (Control.appearance.ToLower() == "signature" || Control.appearance.ToLower() == "draw") { int width = MainCanvas.Width; int height = MainCanvas.Height; //canvas image if (TempBitmap != null) { canvasBitmap = Bitmap.CreateScaledBitmap(TempBitmap, width, height, true); } else { canvasBitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888); } if (dv == null) { dv = new DrawingView(this, canvasBitmap, 10, BackgroundImage); } if (Control.appearance.ToLower() != "signature") { SetupEvents(); } var layoutParams = new RelativeLayout.LayoutParams(width, height); layoutParams.AddRule(LayoutRules.CenterInParent); dv.LayoutParameters = layoutParams; MainCanvas.AddView(dv); GC.Collect(); } }