示例#1
0
        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);
        }
示例#2
0
        // シャッターを切った時のコールバック
        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);
            }
        }
示例#3
0
        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();
        }
示例#4
0
        public void AddExifData(string filename)
        {
            using var exif = new ExifInterface(filename);

            exif.SetAttribute(ExifInterface.TagXmp, Xmp);

            exif.SetAttribute(ExifInterface.TagSoftware, "Sketch 360");

            exif.SaveAttributes();
        }
示例#5
0
        private bool InternalResize(string filePath, PhotoSize photoSize, int quality)
        {
            try
            {
                if (photoSize == PhotoSize.Full)
                {
                    return(false);
                }

                var percent = CalculateResizePercent(photoSize);

                var exif     = new ExifInterface(filePath);
                var rotation = GetRotation(exif);

                var options = new BitmapFactory.Options
                {
                    InJustDecodeBounds = true,
                };

                BitmapFactory.DecodeFile(filePath, options);

                var finalWidth  = (int)(options.OutWidth * percent);
                var finalHeight = (int)(options.OutHeight * percent);

                if (rotation % 180 == 90)
                {
                    var tmpSwap = finalWidth;
                    finalWidth  = finalHeight;
                    finalHeight = tmpSwap;
                }

                exif.SetAttribute("PixelXDimension", Java.Lang.Integer.ToString(finalWidth));
                exif.SetAttribute("PixelYDimension", Java.Lang.Integer.ToString(finalHeight));

                options.InSampleSize       = CalculateInSampleSize(options, finalWidth, finalHeight);
                options.InJustDecodeBounds = false;

                PerformResizeWithRotation(filePath, quality, exif, rotation, options);

                ////exif.SaveAttributes();

                GC.Collect();

                return(true);
            }
            catch (Exception ex)
            {
                loggingService.Error(ex);

                return(false);
            }
        }
示例#6
0
        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();
        }
示例#7
0
 public static void Copy(this ExifInterface dest, ExifInterface source)
 {
     foreach (var tagName in tagNames)
     {
         dest.SetAttribute(tagName, source.GetAttribute(tagName));
     }
 }
示例#8
0
        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);
            }
        }
示例#9
0
        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);
        }
示例#10
0
        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);
            }
        }
示例#11
0
 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);
            }
        }
示例#13
0
        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());
            }
        }
示例#15
0
        private void PerformResizeWithRotation(
            string filePath,
            int quality,
            ExifInterface exif,
            int rotation,
            BitmapFactory.Options options)
        {
            using (var originalImage = BitmapFactory.DecodeFile(filePath, options))
            {
                if (rotation != 0)
                {
                    var matrix = new Matrix();
                    matrix.PostRotate(rotation);
                    using (var rotatedImage = Bitmap.CreateBitmap(
                               originalImage,
                               0,
                               0,
                               originalImage.Width,
                               originalImage.Height,
                               matrix,
                               true))
                    {
                        using (var stream = System.IO.File.Open(filePath, FileMode.Create, FileAccess.ReadWrite))
                        {
                            rotatedImage.Compress(Bitmap.CompressFormat.Jpeg, quality, stream);
                            stream.Close();
                        }

                        rotatedImage.Recycle();
                    }

                    exif.SetAttribute(
                        ExifInterface.TagOrientation,
                        Java.Lang.Integer.ToString((int)Orientation.Normal));
                }
                else
                {
                    using (var stream = System.IO.File.Open(filePath, FileMode.Create, FileAccess.ReadWrite))
                    {
                        originalImage.Compress(
                            Bitmap.CompressFormat.Jpeg,
                            quality,
                            stream);
                        stream.Close();
                    }
                }
            }
        }
        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
            }
        }
示例#17
0
        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
            }
        }
示例#18
0
        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);
        }
示例#19
0
        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
            {
            }
        }
示例#21
0
        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;
                }
            }
        }
示例#22
0
        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();
        }
示例#23
0
        /// <summary>
        /// Resize Image Async
        /// </summary>
        /// <param name="filePath">The file image path</param>
        /// <param name="photoSize">Photo size to go to.</param>
        /// <param name="quality">Image quality (1-100)</param>
        /// <param name="customPhotoSize">Custom size in percent</param>
        /// <param name="exif">original metadata</param>
        /// <returns>True if rotation or compression occured, else false</returns>
        public Task <bool> ResizeAsync(string filePath, PhotoSize photoSize, int quality, int customPhotoSize, ExifInterface exif)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                return(Task.FromResult(false));
            }

            try
            {
                return(Task.Run(() =>
                {
                    try
                    {
                        if (photoSize == PhotoSize.Full)
                        {
                            return false;
                        }

                        var percent = 1.0f;
                        switch (photoSize)
                        {
                        case PhotoSize.Large:
                            percent = .75f;
                            break;

                        case PhotoSize.Medium:
                            percent = .5f;
                            break;

                        case PhotoSize.Small:
                            percent = .25f;
                            break;

                        case PhotoSize.Custom:
                            percent = (float)customPhotoSize / 100f;
                            break;
                        }


                        //First decode to just get dimensions
                        var options = new BitmapFactory.Options
                        {
                            InJustDecodeBounds = true
                        };

                        //already on background task
                        BitmapFactory.DecodeFile(filePath, options);

                        var finalWidth = (int)(options.OutWidth * percent);
                        var finalHeight = (int)(options.OutHeight * percent);

                        //set scaled image dimensions
                        exif?.SetAttribute(TAG_PIXEL_X_DIMENSION, Java.Lang.Integer.ToString(finalWidth));
                        exif?.SetAttribute(TAG_PIXEL_Y_DIMENSION, Java.Lang.Integer.ToString(finalHeight));

                        //calculate sample size
                        options.InSampleSize = CalculateInSampleSize(options, finalWidth, finalHeight);

                        //turn off decode
                        options.InJustDecodeBounds = false;


                        //this now will return the requested width/height from file, so no longer need to scale
                        using (var originalImage = BitmapFactory.DecodeFile(filePath, options))
                        {
                            //always need to compress to save back to disk
                            using (var stream = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite))
                            {
                                originalImage.Compress(Bitmap.CompressFormat.Jpeg, quality, stream);
                                stream.Close();
                            }

                            originalImage.Recycle();

                            // Dispose of the Java side bitmap.
                            GC.Collect();
                            return true;
                        }
                    }
                    catch (Exception ex)
                    {
#if DEBUG
                        throw ex;
#else
                        return false;
#endif
                    }
                }));
            }
            catch (Exception ex)
            {
#if DEBUG
                throw ex;
#else
                return(Task.FromResult(false));
#endif
            }
        }
        /// <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);
        }
示例#25
0
        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);
                }
            }
        }
示例#26
0
        /// <summary>
        ///  Rotate an image if required and saves it back to disk.
        /// </summary>
        /// <param name="filePath">The file image path</param>
        /// <param name="mediaOptions">The options.</param>
        /// <param name="exif">original metadata</param>
        /// <returns>True if rotation or compression occured, else false</returns>
        public Task <bool> FixOrientationAndResizeAsync(string filePath, StoreCameraMediaOptions mediaOptions, ExifInterface exif)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                return(Task.FromResult(false));
            }

            try
            {
                return(Task.Run(() =>
                {
                    try
                    {
                        var rotation = GetRotation(exif);

                        // if we don't need to rotate, aren't resizing, and aren't adjusting quality then simply return
                        if (rotation == 0 && mediaOptions.PhotoSize == PhotoSize.Full && mediaOptions.CompressionQuality == 100)
                        {
                            return false;
                        }

                        var percent = 1.0f;
                        switch (mediaOptions.PhotoSize)
                        {
                        case PhotoSize.Large:
                            percent = .75f;
                            break;

                        case PhotoSize.Medium:
                            percent = .5f;
                            break;

                        case PhotoSize.Small:
                            percent = .25f;
                            break;

                        case PhotoSize.Custom:
                            percent = (float)mediaOptions.CustomPhotoSize / 100f;
                            break;
                        }

                        //First decode to just get dimensions
                        var options = new BitmapFactory.Options
                        {
                            InJustDecodeBounds = true
                        };

                        //already on background task
                        BitmapFactory.DecodeFile(filePath, options);

                        if (mediaOptions.PhotoSize == PhotoSize.MaxWidthHeight && mediaOptions.MaxWidthHeight.HasValue)
                        {
                            var max = Math.Max(options.OutWidth, options.OutHeight);
                            if (max > mediaOptions.MaxWidthHeight)
                            {
                                percent = (float)mediaOptions.MaxWidthHeight / (float)max;
                            }
                        }

                        var finalWidth = (int)(options.OutWidth * percent);
                        var finalHeight = (int)(options.OutHeight * percent);

                        //calculate sample size
                        options.InSampleSize = CalculateInSampleSize(options, finalWidth, finalHeight);

                        //turn off decode
                        options.InJustDecodeBounds = false;


                        //this now will return the requested width/height from file, so no longer need to scale
                        var originalImage = BitmapFactory.DecodeFile(filePath, options);

                        if (originalImage == null)
                        {
                            return false;
                        }

                        if (finalWidth != originalImage.Width || finalHeight != originalImage.Height)
                        {
                            originalImage = Bitmap.CreateScaledBitmap(originalImage, finalWidth, finalHeight, true);
                        }
                        if (rotation % 180 == 90)
                        {
                            var a = finalWidth;
                            finalWidth = finalHeight;
                            finalHeight = a;
                        }

                        //set scaled and rotated image dimensions
                        exif?.SetAttribute(TAG_PIXEL_X_DIMENSION, Java.Lang.Integer.ToString(finalWidth));
                        exif?.SetAttribute(TAG_PIXEL_Y_DIMENSION, Java.Lang.Integer.ToString(finalHeight));

                        //if we need to rotate then go for it.
                        //then compresse it if needed
                        if (rotation != 0)
                        {
                            var matrix = new Matrix();
                            matrix.PostRotate(rotation);
                            using (var rotatedImage = Bitmap.CreateBitmap(originalImage, 0, 0, originalImage.Width, originalImage.Height, matrix, true))
                            {
                                //always need to compress to save back to disk
                                using (var stream = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite))
                                {
                                    rotatedImage.Compress(Bitmap.CompressFormat.Jpeg, mediaOptions.CompressionQuality, stream);
                                    stream.Close();
                                }
                                rotatedImage.Recycle();
                            }
                            //change the orienation to "not rotated"
                            exif?.SetAttribute(ExifInterface.TagOrientation, Java.Lang.Integer.ToString((int)Orientation.Normal));
                        }
                        else
                        {
                            //always need to compress to save back to disk
                            using (var stream = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite))
                            {
                                originalImage.Compress(Bitmap.CompressFormat.Jpeg, mediaOptions.CompressionQuality, stream);
                                stream.Close();
                            }
                        }

                        originalImage.Recycle();
                        originalImage.Dispose();
                        // Dispose of the Java side bitmap.
                        GC.Collect();
                        return true;
                    }
                    catch (Exception ex)
                    {
#if DEBUG
                        throw ex;
#else
                        return false;
#endif
                    }
                }));
            }
            catch (Exception ex)
            {
#if DEBUG
                throw ex;
#else
                return(Task.FromResult(false));
#endif
            }
        }
示例#27
0
        private string GetLocationForExif(ExifInterface exif)
        {
            string          exifExtraData   = string.Empty;
            var             activity        = (MainActivity)CrossCurrentActivity.Current.Activity;
            LocationManager locationManager = activity.locationManager;
            var             criteria        = new Criteria {
                PowerRequirement = Power.Medium
            };

            var bestProvider = locationManager.GetBestProvider(criteria, true);
            var location     = locationManager.GetLastKnownLocation(bestProvider);

            if (location != null)
            {
                string locProvider = location.Provider;
                long   newlastfix  = location.Time;
                bool   uniqueFix   = newlastfix != lastfix;
                lastfix       = newlastfix;
                exifExtraData = "loc=" + locProvider + "," + "uniqueLocFix=" + uniqueFix + ",";;
                double locLat = location.Latitude;
                double locLon = location.Longitude;

                try
                {
                    int    num1Lat = (int)Math.Floor(locLat);
                    int    num2Lat = (int)Math.Floor((locLat - num1Lat) * 60);
                    double num3Lat = (locLat - ((double)num1Lat + ((double)num2Lat / 60))) * 3600000;

                    int    num1Lon = (int)Math.Floor(locLon);
                    int    num2Lon = (int)Math.Floor((locLon - num1Lon) * 60);
                    double num3Lon = (locLon - ((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 (locLat > 0)
                    {
                        exif.SetAttribute(ExifInterface.TagGpsLatitudeRef, "N");
                    }
                    else
                    {
                        exif.SetAttribute(ExifInterface.TagGpsLatitudeRef, "S");
                    }

                    if (locLon > 0)
                    {
                        exif.SetAttribute(ExifInterface.TagGpsLongitudeRef, "E");
                    }
                    else
                    {
                        exif.SetAttribute(ExifInterface.TagGpsLongitudeRef, "W");
                    }
                }
                catch (Exception e)
                {
                }
            }



            return(exifExtraData);
        }
示例#28
0
        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, "", "");
        }