Esempio n. 1
0
        private async Task <OperationResult <UUIDModel> > UploadMedia(GalleryMediaModel model)
        {
            model.UploadState = UploadState.UploadStart;
            System.IO.Stream stream          = null;
            FileInputStream  fileInputStream = null;

            try
            {
                var photo = new Java.IO.File(model.TempPath);
                fileInputStream = new FileInputStream(photo);
                stream          = new StreamConverter(fileInputStream, null);

                var request      = new UploadMediaModel(AppSettings.User.UserInfo, stream, System.IO.Path.GetExtension(model.TempPath));
                var serverResult = await Presenter.TryUploadMedia(request);

                model.UploadState = UploadState.UploadEnd;
                return(serverResult);
            }
            catch (Exception ex)
            {
                model.UploadState = UploadState.UploadError;
                await AppSettings.Logger.Error(ex);

                return(new OperationResult <UUIDModel>(new InternalException(LocalizationKeys.PhotoUploadError, ex)));
            }
            finally
            {
                fileInputStream?.Close(); // ??? change order?
                stream?.Flush();
                fileInputStream?.Dispose();
                stream?.Dispose();
            }
        }
        private void LoadThumbnail(GalleryMediaModel model)
        {
            if (_cts != null && !_cts.IsCancellationRequested)
            {
                _cts.Cancel();
            }

            _cts = new CancellationTokenSource();
            var token = _cts.Token;

            Task.Run(() =>
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }

                var thumbnail = MediaStore.Images.Thumbnails.GetThumbnail(Context.ContentResolver, model.Id, ThumbnailKind.MiniKind, null);

                if (token.IsCancellationRequested)
                {
                    thumbnail.Recycle();
                    return;
                }

                _handler.Post(() => SetImageBitmap(thumbnail));
            }, token);
        }
Esempio n. 3
0
        public async Task Bind(GalleryMediaModel model)
        {
            BitmapUtils.ReleaseBitmap(Drawable);
            SetImageDrawable(DefaultColor);

            _model = model;
            _model.ModelChanged = Invalidate;
            await LoadThumbnail(_model);
        }
Esempio n. 4
0
            public void Update(GalleryMediaModel model)
            {
                BitmapUtils.ReleaseBitmap(_image.Drawable);

                _image.SetImageBitmap(null);
                _image.SetImageResource(Style.R245G245B245);

                if (model.UploadState > UploadState.ReadyToSave)
                {
                    var bitmap = BitmapUtils.DecodeSampledBitmapFromFile(ItemView.Context, Android.Net.Uri.Parse(model.TempPath), Style.GalleryHorizontalScreenWidth, Style.GalleryHorizontalHeight);
                    _image.SetImageBitmap(bitmap);
                }
            }
        public void Bind(GalleryMediaModel model)
        {
            if (_model != null)
            {
                _model.ModelChanged -= ModelChanged;
                (Drawable as BitmapDrawable)?.Bitmap?.Recycle();
                SetImageDrawable(new ColorDrawable(Style.R245G245B245));
            }

            _model = model;
            _model.ModelChanged += ModelChanged;
            LoadThumbnail(_model);
        }
Esempio n. 6
0
        public void HandleSharingPhoto(Intent intent)
        {
            var uri = (Android.Net.Uri)intent.GetParcelableExtra(SharingPhotoData);

            intent.RemoveExtra(SharingPhotoData);
            if (uri != null)
            {
                var galleryModel = new GalleryMediaModel
                {
                    Path = BitmapUtils.GetUriRealPath(this, uri)
                };
                OpenNewContentFragment(new PreviewPostCreateFragment(galleryModel));
            }
        }
        private void MultiselectBtnOnClick(object sender, EventArgs eventArgs)
        {
            if (!_preview.IsBitmapReady)
            {
                return;
            }

            _multiSelect             = !_multiSelect;
            _ratioBtn.Visibility     = _multiSelect ? ViewStates.Gone : ViewStates.Visible;
            _preview.UseStrictBounds = _multiSelect;

            foreach (var model in _gallery)
            {
                model.MultySelect       = _multiSelect;
                model.SelectionPosition = 0;
            }

            GalleryMediaModel selectedItem = null;

            for (var i = 0; i < _pickedItems.Count; i++)
            {
                if (_pickedItems[i].Selected)
                {
                    selectedItem = _pickedItems[i];
                    if (_multiSelect)
                    {
                        selectedItem.Parameters = _preview.DrawableImageParameters.Copy();
                        continue;
                    }
                }

                _pickedItems[i].Parameters = null;
            }

            _pickedItems.Clear();
            _prevSelected = null;

            if (selectedItem == null)
            {
                selectedItem = _buckets[0].Equals(_selectedBucket)
                    ? _gallery.FirstOrDefault()
                    : _gallery.FirstOrDefault(m => m.Bucket.Equals(_selectedBucket, StringComparison.OrdinalIgnoreCase));
            }

            OnItemSelected(selectedItem, 0);
            _multiselectBtn.SetImageResource(_multiSelect ? Resource.Drawable.ic_multiselect_active : Resource.Drawable.ic_multiselect);

            _gridAdapter.NotifyDataSetChanged();
        }
        private void OnItemSelected(GalleryMediaModel model)
        {
            if (_pickedItems.Count >= MaxPhotosAllowed && model.SelectionPosition == (int)GallerySelectionType.Multi)
            {
                Activity.ShowAlert(LocalizationKeys.PickedPhotosLimit);
                return;
            }
            var selected = _pickedItems.Find(x => x.Selected && x != model);

            if (selected != null)
            {
                selected.Selected = false;
            }
            if (_multiSelect)
            {
                if (_prevSelected != null)
                {
                    _prevSelected.Parameters = _preview.DrawableImageParameters.Copy();
                }
                _prevSelected = model;

                if (!_pickedItems.Contains(model))
                {
                    _pickedItems.Add(model);
                    model.SelectionPosition = _pickedItems.Count;
                }
                else if (model.Selected)
                {
                    _pickedItems.Remove(model);
                    _pickedItems.ForEach(x => x.SelectionPosition = _pickedItems.IndexOf(x) + 1);
                    model.Selected          = false;
                    model.SelectionPosition = (int)GallerySelectionType.Multi;
                    if (_pickedItems.Count > 0)
                    {
                        OnItemSelected(_pickedItems.Last());
                    }
                    return;
                }
            }
            else
            {
                _pickedItems.Clear();
                _pickedItems.Add(model);
            }

            model.Selected = true;
            _preview.SetImageUri(Uri.Parse(model.Path), model.Parameters);
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            AppDomain.CurrentDomain.UnhandledException  -= OnCurrentDomainOnUnhandledException;
            TaskScheduler.UnobservedTaskException       -= OnTaskSchedulerOnUnobservedTaskException;
            AndroidEnvironment.UnhandledExceptionRaiser -= OnUnhandledExceptionRaiser;

            AppDomain.CurrentDomain.UnhandledException  += OnCurrentDomainOnUnhandledException;
            TaskScheduler.UnobservedTaskException       += OnTaskSchedulerOnUnobservedTaskException;
            AndroidEnvironment.UnhandledExceptionRaiser += OnUnhandledExceptionRaiser;

            GAService.Instance.InitializeGAService(this);
            InitPushes();

            switch (Intent.Action)
            {
            case Intent.ActionSend:
            {
                if (AppSettings.User.IsAuthenticated)
                {
                    var uri = (Android.Net.Uri)Intent.GetParcelableExtra(Intent.ExtraStream);
                    var fragmentTransaction = SupportFragmentManager.BeginTransaction();
                    var galleryModel        = new GalleryMediaModel
                    {
                        Path = BitmapUtils.GetUriRealPath(this, uri)
                    };
                    CurrentHostFragment = HostFragment.NewInstance(new PostCreateFragment(galleryModel));
                    fragmentTransaction.Add(Android.Resource.Id.Content, CurrentHostFragment);
                    fragmentTransaction.Commit();
                }
                else
                {
                    StartActivity(typeof(PreSignInActivity));
                }
                return;
            }

            case Intent.ActionView:
            {
                var intent = new Intent(this, AppSettings.User.IsAuthenticated ? typeof(RootActivity) : typeof(GuestActivity));
                intent.PutExtra(AppLinkingExtra, Intent?.Data?.Path);
                StartActivity(intent);
                return;
            }
            }
            StartActivity(AppSettings.User.IsAuthenticated ? typeof(RootActivity) : typeof(GuestActivity));
        }
 public void Bind(GalleryMediaModel model)
 {
     if (_model != null)
     {
         _model.ModelChanged -= ModelChanged;
     }
     _model = model;
     _model.ModelChanged += ModelChanged;
     if (!string.IsNullOrEmpty(model.Thumbnail))
     {
         SetImageURI(Uri.Parse(model.Thumbnail));
     }
     else
     {
         SetImageBitmap(null);
     }
 }
Esempio n. 11
0
        private Task LoadThumbnail(GalleryMediaModel model)
        {
            return(Task.Run(() =>
            {
                var thumbnail = MediaStore.Images.Thumbnails.GetThumbnail(Context.ContentResolver, model.Id, ThumbnailKind.MiniKind, _options);
                if (thumbnail == null || _model == null || model.Id != _model.Id)
                {
                    return;
                }

                if (model.Orientation == 0)
                {
                    _handler.Post(() =>
                    {
                        if (_model == null || model.Id != _model.Id)
                        {
                            return;
                        }

                        BitmapUtils.ReleaseBitmap(Drawable);
                        SetImageBitmap(thumbnail);
                    });
                    return;
                }

                var matrix = new Matrix();
                matrix.PostRotate(model.Orientation);
                var oriThumbnail = Bitmap.CreateBitmap(thumbnail, 0, 0, thumbnail.Width, thumbnail.Height, matrix, false);

                BitmapUtils.ReleaseBitmap(thumbnail);

                _handler.Post(() =>
                {
                    if (_model == null || model.Id != _model.Id)
                    {
                        return;
                    }

                    BitmapUtils.ReleaseBitmap(Drawable);
                    SetImageBitmap(oriThumbnail);
                });
            }));
        }
        public void OnPictureTaken(byte[] data, Camera camera)
        {
            Task.Run(() =>
            {
                var directory = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim);
                var photoUri  = $"{directory}/{Guid.NewGuid()}.jpeg";

                var stream = new Java.IO.FileOutputStream(photoUri);
                stream.Write(data);
                stream.Close();

                var exifInterface = new ExifInterface(photoUri);
                var orientation   = exifInterface.GetAttributeInt(ExifInterface.TagOrientation, 0);

                if (orientation != 1 && orientation != 0)
                {
                    var bitmap         = BitmapFactory.DecodeByteArray(data, 0, data.Length);
                    bitmap             = BitmapUtils.RotateImage(bitmap, _rotationOnShutter);
                    var rotationStream = new System.IO.FileStream(photoUri, System.IO.FileMode.Create);
                    bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, rotationStream);
                }

                var model = new GalleryMediaModel
                {
                    Path = photoUri
                };

                Activity.RunOnUiThread(() =>
                {
                    ((BaseActivity)Activity).OpenNewContentFragment(new PostEditFragment(model));
                    if (_progressBar != null)
                    {
                        _progressBar.Visibility = ViewStates.Gone;
                        _shotButton.Visibility  = ViewStates.Visible;
                        _flashButton.Enabled    = true;
                        _galleryButton.Enabled  = true;
                        _revertButton.Enabled   = true;
                        _closeButton.Enabled    = true;
                    }
                });
            });
        }
Esempio n. 13
0
        private void MultiselectBtnOnClick(object sender, EventArgs eventArgs)
        {
            _multiSelect             = !_multiSelect;
            _ratioBtn.Visibility     = _multiSelect ? ViewStates.Gone : ViewStates.Visible;
            _preview.UseStrictBounds = _multiSelect;
            _gallery[_selectedBucket].ForEach(x => x.SelectionPosition = _multiSelect ? (int)GallerySelectionType.Multi : (int)GallerySelectionType.None);
            GalleryMediaModel selectedItem = null;

            _pickedItems.ForEach(x =>
            {
                if (x.Selected)
                {
                    selectedItem = x;
                }
                x.Parameters = null;
            });
            _pickedItems.Clear();
            _prevSelected = null;
            OnItemSelected(selectedItem ?? _gallery[_selectedBucket][0]);
            _multiselectBtn.SetImageResource(_multiSelect ? Resource.Drawable.ic_multiselect_active : Resource.Drawable.ic_multiselect);
        }
Esempio n. 14
0
        private List <GalleryMediaModel> GetMediaWithThumbnails()
        {
            var result = new List <GalleryMediaModel>();

            foreach (var tuple in _media)
            {
                var galleryModel = new GalleryMediaModel
                {
                    Id        = tuple.Key,
                    Path      = "file://" + tuple.Value,
                    Thumbnail = _thumbnails.ContainsKey(tuple.Key) ? _thumbnails[tuple.Key] : string.Empty,
                    Selected  = false
                };
                if (string.IsNullOrEmpty(galleryModel.Thumbnail))
                {
                    GenerateThumbnail(_selectedBucket, galleryModel, _cancellationTokenSource.Token);
                }
                result.Add(galleryModel);
            }
            return(result);
        }
Esempio n. 15
0
        private void InitGalery()
        {
            string[] columns =
            {
                MediaStore.Images.ImageColumns.Id,
                MediaStore.Images.ImageColumns.Data,
                MediaStore.Images.ImageColumns.BucketDisplayName,
                MediaStore.Images.ImageColumns.Orientation
            };

            var orderBy = $"{MediaStore.Images.ImageColumns.DateTaken} DESC";
            var cursor  = Activity.ContentResolver.Query(MediaStore.Images.Media.ExternalContentUri, columns, null, null, orderBy);

            if (cursor != null)
            {
                var count             = cursor.Count;
                var idColumnIndex     = cursor.GetColumnIndex(MediaStore.Images.ImageColumns.Id);
                var dataColumnIndex   = cursor.GetColumnIndex(MediaStore.Images.ImageColumns.Data);
                var oriColumnIndex    = cursor.GetColumnIndex(MediaStore.Images.ImageColumns.Orientation);
                var bucketDisplayName = cursor.GetColumnIndex(MediaStore.Images.ImageColumns.BucketDisplayName);
                _gallery = new GalleryMediaModel[count];

                for (var i = 0; i < count; i++)
                {
                    cursor.MoveToPosition(i);
                    _gallery[i] = new GalleryMediaModel
                    {
                        Id          = cursor.GetLong(idColumnIndex),
                        Path        = cursor.GetString(dataColumnIndex),
                        Bucket      = cursor.GetString(bucketDisplayName),
                        Orientation = cursor.GetInt(oriColumnIndex)
                    };
                }
                cursor.Close();
            }
            else
            {
                _gallery = new GalleryMediaModel[0];
            }
        }
Esempio n. 16
0
        private void GenerateThumbnail(string bucket, GalleryMediaModel model, CancellationToken ct) => Task.Run(() =>
        {
            var thumbnail = MediaStore.Images.Thumbnails.GetThumbnail(Activity.ContentResolver, long.Parse(model.Id),
                                                                      ThumbnailKind.MiniKind, null);

            var values = new ContentValues(4);
            values.Put(MediaStore.Images.Thumbnails.Kind, (int)ThumbnailKind.MiniKind);
            values.Put(MediaStore.Images.Thumbnails.ImageId, long.Parse(model.Id));
            values.Put(MediaStore.Images.Thumbnails.Height, thumbnail.Height);
            values.Put(MediaStore.Images.Thumbnails.Width, thumbnail.Width);

            if (ct.IsCancellationRequested)
            {
                return;
            }

            var uri = Activity.ContentResolver.Insert(MediaStore.Images.Thumbnails.ExternalContentUri, values);

            using (var thumbOut = Activity.ContentResolver.OpenOutputStream(uri))
            {
                thumbnail.Compress(Bitmap.CompressFormat.Jpeg, 100, thumbOut);
            }

            var cursor = MediaStore.Images.Thumbnails.QueryMiniThumbnail(Activity.ContentResolver, long.Parse(model.Id),
                                                                         ThumbnailKind.MiniKind, new[] { MediaStore.Images.Thumbnails.Data });

            if (cursor != null && cursor.Count > 0)
            {
                cursor.MoveToFirst();
                var thumbUri    = cursor.GetString(0);
                model.Thumbnail = thumbUri;
                Activity.RunOnUiThread(() =>
                                       GridAdapter.NotifyItemChanged(_gallery[bucket].IndexOf(model)));
                cursor.Close();
            }
        }, ct);
Esempio n. 17
0
 public void Update(GalleryMediaModel model)
 {
     _image.SetImageBitmap(model.PreparedBitmap);
 }
Esempio n. 18
0
 public void Update(GalleryMediaModel media)
 {
     _media = media;
     _image?.Bind(media);
 }
Esempio n. 19
0
        public string CropAndSave(GalleryMediaModel model)
        {
            FileStream stream = null;
            Bitmap     sized  = null;
            Bitmap     croped = null;

            try
            {
                var parameters    = model.Parameters;
                var rotation      = parameters.Rotation;
                var previewBounds = parameters.PreviewBounds;
                var cropBounds    = parameters.CropBounds;

                var options = new BitmapFactory.Options {
                    InJustDecodeBounds = true
                };
                BitmapFactory.DecodeFile(model.Path, options);

                var pWidth = (int)Math.Round((previewBounds.Right - previewBounds.Left) / parameters.Scale);
                var dZ     = (rotation % 180 > 0 ? options.OutHeight : options.OutWidth) / (float)pWidth;

                var width  = (int)Math.Round((cropBounds.Right - cropBounds.Left) * dZ / parameters.Scale);
                var height = (int)Math.Round((cropBounds.Bottom - cropBounds.Top) * dZ / parameters.Scale);
                var x      = (int)Math.Max(Math.Round(-previewBounds.Left * dZ / parameters.Scale), 0);
                var y      = (int)Math.Max(Math.Round(-previewBounds.Top * dZ / parameters.Scale), 0);

                var sampleSize = BitmapUtils.CalculateInSampleSize(width, height, BitmapUtils.MaxImageSize, BitmapUtils.MaxImageSize);

                width  = width / sampleSize;
                height = height / sampleSize;
                x      = x / sampleSize;
                y      = y / sampleSize;

                options.InSampleSize             = sampleSize;
                options.InJustDecodeBounds       = false;
                options.InPreferQualityOverSpeed = true;
                sized = BitmapFactory.DecodeFile(model.Path, options);


                switch (rotation)
                {
                case 90:
                {
                    var b = width;
                    width  = height;
                    height = b;

                    b = x;
                    x = y;
                    y = sized.Height - b - height;
                    break;
                }

                case 180:
                {
                    x = sized.Width - width - x;
                    y = sized.Height - height - y;
                    break;
                }

                case 270:
                {
                    var b = width;
                    width  = height;
                    height = b;

                    b = y;
                    y = x;
                    x = sized.Width - b - width;
                    break;
                }
                }

                x = Math.Max(x, 0);
                y = Math.Max(y, 0);

                if (x + width > sized.Width)
                {
                    width = sized.Width - x;
                }
                if (y + height > sized.Height)
                {
                    height = sized.Height - y;
                }

                var matrix = new Matrix();
                matrix.SetRotate(rotation);

                croped = Bitmap.CreateBitmap(sized, x, y, width, height, matrix, true);

                var directory = new Java.IO.File(Context.CacheDir, Constants.Steepshot);
                if (!directory.Exists())
                {
                    directory.Mkdirs();
                }

                var outPath = $"{directory}/{Guid.NewGuid()}.jpeg";
                stream = new FileStream(outPath, FileMode.Create);
                croped.Compress(Bitmap.CompressFormat.Jpeg, 99, stream);

                var args = new Dictionary <string, string>
                {
                    { ExifInterface.TagImageLength, croped.Height.ToString() },
                    { ExifInterface.TagImageWidth, croped.Width.ToString() },
                    { ExifInterface.TagOrientation, "1" },
                };

                BitmapUtils.CopyExif(model.Path, outPath, args);

                return(outPath);
            }
            catch (Exception ex)
            {
                AppSettings.Logger.Error(ex);
                return(string.Empty);
            }
            finally
            {
                stream?.Dispose();
                BitmapUtils.ReleaseBitmap(sized);
                BitmapUtils.ReleaseBitmap(croped);
            }
        }
Esempio n. 20
0
 public PostCreateFragment(GalleryMediaModel media)
 {
     _media = new List <GalleryMediaModel> {
         media
     };
 }
Esempio n. 21
0
        private void OnItemSelected(GalleryMediaModel model)
        {
            if (_multiSelect && _pickedItems.Count >= MaxPhotosAllowed && !(model.Selected || model.SelectionPosition > 0))
            {
                Activity.ShowAlert(LocalizationKeys.PickedPhotosLimit, ToastLength.Short);
                return;
            }

            for (int i = 0; i < _pickedItems.Count; i++)
            {
                var selected = _pickedItems[i];
                if (selected.Selected && selected != model)
                {
                    selected.Selected = false;
                }
            }

            if (_multiSelect)
            {
                if (_prevSelected != null)
                {
                    _prevSelected.Parameters = _preview.DrawableImageParameters.Copy();
                }

                _prevSelected = model;

                if (!_pickedItems.Contains(model))
                {
                    _pickedItems.Add(model);
                    model.SelectionPosition = _pickedItems.Count;
                }
                else if (model.Selected)
                {
                    model.Parameters        = null;
                    model.Selected          = false;
                    model.SelectionPosition = 0;
                    _prevSelected           = null;
                    _pickedItems.Remove(model);

                    for (var index = 0; index < _pickedItems.Count; index++)
                    {
                        var x = _pickedItems[index];
                        x.SelectionPosition = index + 1;
                    }

                    GalleryMediaModel selectedItem;
                    if (_pickedItems.Count > 0)
                    {
                        selectedItem = _pickedItems.Last();
                    }
                    else
                    {
                        selectedItem = _buckets[0].Equals(_selectedBucket)
                            ? _gallery.FirstOrDefault()
                            : _gallery.FirstOrDefault(m => m.Bucket.Equals(_selectedBucket, StringComparison.OrdinalIgnoreCase));
                    }

                    if (!_multiSelect || _pickedItems.Count > 0)
                    {
                        OnItemSelected(selectedItem);
                    }
                    return;
                }
            }
            else
            {
                _pickedItems.Clear();
                _pickedItems.Add(model);
            }

            model.Selected = true;
            _preview.SetImagePath(model.Path, model.Parameters);
        }
Esempio n. 22
0
 public PreviewPostCreateFragment(GalleryMediaModel media)
     : base(new List <GalleryMediaModel> {
     media
 })
 {
 }