protected override void OnActivityResult(int requestCode, Result resultCode,
                                                 Intent resultData)
        {
            if (resultCode == Result.Ok)
            {
                // The document selected by the user won't be returned in the intent.
                // Instead, a URI to that document will be contained in the return intent
                // provided to this method as a parameter.
                // Pull that URI using resultData.getData().
                Uri uri = null;
                if (resultData != null)
                {
                    uri = resultData.Data;

                    ParcelFileDescriptor parcelFileDescriptor =
                        ContentResolver.OpenFileDescriptor(uri, "r");
                    FileDescriptor fileDescriptor = parcelFileDescriptor.FileDescriptor;
                    Bitmap         image          = BitmapFactory.DecodeFileDescriptor(fileDescriptor);
                    parcelFileDescriptor.Close();

                    var store = IsolatedStorageFile.GetUserStoreForApplication();
                    if (store.FileExists(Path))
                    {
                        store.DeleteFile(Path);
                    }

                    var          fs     = store.CreateFile(Path);
                    MemoryStream buffer = new MemoryStream();
                    image.Compress(Bitmap.CompressFormat.Png, 100, buffer);
                    buffer.Seek(0, SeekOrigin.Begin);
                    byte[] bytes = new byte[(int)buffer.Length];
                    buffer.Read(bytes, 0, (int)buffer.Length);

                    fs.Write(bytes, 0, bytes.Length);
                    fs.Close();
                    Texture2D text  = null;
                    var       file2 = store.OpenFile(Path, FileMode.Open);

                    text = Texture2D.FromStream(Game1.self.GraphicsDevice, file2);
                    file2.Close();
                    file2.Dispose();

                    Game1.self.config.listOfCards.Single(p => p.Name == Path).SkinPath = Path;
                    Game1.self.ShipsSkins.Single(p => p.ship == Path).skin             = Game1.self.loadTexture2D(Path);
                    var           file   = store.OpenFile("Config_Cards", FileMode.Open);
                    TextWriter    writer = new StreamWriter(file);
                    XmlSerializer xml    = new XmlSerializer(typeof(Cards));
                    xml.Serialize(writer, Game1.self.config);
                    writer.Close();
                    file.Close();
                    store.Close();
                }
            }
        }
Exemplo n.º 2
0
 public static void GetMetadataFromContentURI(this Android.Net.Uri uri, ContentResolver contentResolver, out long size, out string fileName)
 {
     using (var fd = contentResolver.OpenFileDescriptor(uri, "r"))
         size = fd.StatSize;
     using (var cursor = contentResolver.Query(uri, new string[] {
         Android.Provider.OpenableColumns.DisplayName
     }, null, null, null))
     {
         cursor.MoveToFirst();
         fileName = GetFixedFileName(cursor.GetString(0), contentResolver.GetType(uri));
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// Return file path for specified uri using CacheDir
        /// </summary>
        /// <param name="context">Current context</param>
        /// <param name="uri">Specified uri</param>
        /// <returns>Drive File absolute path</returns>
        private static string GetDriveFileAbsolutePath(Context context, global::Android.Net.Uri uri)
        {
            ICursor          cursor = null;
            FileInputStream  input  = null;
            FileOutputStream output = null;

            try
            {
                cursor = context.ContentResolver.Query(uri, new string[] { OpenableColumns.DisplayName }, null, null, null);
                if (cursor != null && cursor.MoveToFirst())
                {
                    int column_index = cursor.GetColumnIndexOrThrow(OpenableColumns.DisplayName);
                    var fileName     = cursor.GetString(column_index);

                    if (uri == null)
                    {
                        return(null);
                    }
                    ContentResolver resolver = context.ContentResolver;

                    string outputFilePath    = new Java.IO.File(context.CacheDir, fileName).AbsolutePath;
                    ParcelFileDescriptor pfd = resolver.OpenFileDescriptor(uri, "r");
                    FileDescriptor       fd  = pfd.FileDescriptor;
                    input  = new FileInputStream(fd);
                    output = new FileOutputStream(outputFilePath);
                    int    read  = 0;
                    byte[] bytes = new byte[4096];
                    while ((read = input.Read(bytes)) != -1)
                    {
                        output.Write(bytes, 0, read);
                    }

                    return(new Java.IO.File(outputFilePath).AbsolutePath);
                }
            }
            catch (Java.IO.IOException ignored)
            {
                // nothing we can do
            }
            finally
            {
                if (cursor != null)
                {
                    cursor.Close();
                }

                input.Close();
                output.Close();
            }

            return(string.Empty);
        }
Exemplo n.º 4
0
        private async Task CreateCopy(Uri sourceUri, Uri destinationUri)
        {
            using (var source = new FileInputStream(ContentResolver.OpenFileDescriptor(sourceUri, "r").FileDescriptor))
            {
                using (var destination = new FileOutputStream(ContentResolver.OpenFileDescriptor(destinationUri, "w").FileDescriptor))
                {
                    byte[] content = new byte[source.Available()];
                    await source.ReadAsync(content);

                    await destination.WriteAsync(content);

                    destination.Close();
                }
            }
        }
Exemplo n.º 5
0
        private Payload CreatePayload(Uri uri)
        {
            try
            {
                using (var fd = ContentResolver.OpenFileDescriptor(uri, "r"))
                    this.max = fd.StatSize;

                var inputStream = ContentResolver.OpenInputStream(uri);

                return(Payload.FromStream(inputStream));
            }
            catch (System.Exception e)
            {
                Log("Cannot read file: " + e.Message);
                return(null);
            }
        }
Exemplo n.º 6
0
        private string Compress(string path)
        {
            var photoUri = Android.Net.Uri.Parse(path);

            FileDescriptor fileDescriptor = null;
            Bitmap         btmp           = null;

            System.IO.FileStream stream = null;
            try
            {
                fileDescriptor = ContentResolver.OpenFileDescriptor(photoUri, "r").FileDescriptor;
                btmp           = BitmapUtils.DecodeSampledBitmapFromDescriptor(fileDescriptor, 1600, 1600);
                btmp           = BitmapUtils.RotateImageIfRequired(btmp, fileDescriptor, path);

                var directoryPictures = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures);
                var directory         = new Java.IO.File(directoryPictures, Constants.Steepshot);
                if (!directory.Exists())
                {
                    directory.Mkdirs();
                }

                path   = $"{directory}/{Guid.NewGuid()}.jpeg";
                stream = new System.IO.FileStream(path, System.IO.FileMode.Create);
                btmp.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);

                return(path);
            }
            catch (Exception ex)
            {
                _postButton.Enabled = false;
                this.ShowAlert(Localization.Errors.UnknownCriticalError);
                AppSettings.Reporter.SendCrash(ex);
            }
            finally
            {
                fileDescriptor?.Dispose();
                btmp?.Recycle();
                btmp?.Dispose();
                stream?.Dispose();
            }
            return(path);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Loads a <see cref="Bitmap"/> from the provided <see cref="Android.Net.Uri"/> using the provided <see cref="ContentResolver"/>.
        /// </summary>
        /// <param name="contentResolver">A <see cref="ContentResolver"/> to use to load the image.</param>
        /// <param name="uri">A <see cref="Android.Net.Uri"/> that identifies the image.</param>
        /// <param name="reqWidth">The requested width for the loaded <see cref="Bitmap"/>. The actual width after the bitmap is loaded may be larger, but will not be smaller.</param>
        /// <param name="reqHeight">The requested height for the loaded <see cref="Bitmap"/>. The actual height after the bitmap is loaded may be larger, but will not be smaller.</param>
        /// <returns></returns>
        public static Bitmap GetBitmapFromUri(ContentResolver contentResolver, AndroidUri uri, int reqWidth, int reqHeight)
        {
            ParcelFileDescriptor parcelFileDescriptor = contentResolver.OpenFileDescriptor(uri, "r");
            FileDescriptor       fileDescriptor       = parcelFileDescriptor.FileDescriptor;

            // Load just the dimensions of the image (doesn't actually allocate memory for the bitmap)
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.InJustDecodeBounds = true;
            BitmapFactory.DecodeFileDescriptor(fileDescriptor, null, options);

            // Calculate inSampleSize so we can subsample the image appropriately.
            options.InSampleSize = CalculateInSampleSize(options.OutWidth, options.OutHeight, reqWidth, reqHeight);

            // Load the image into a Bitmap at the determined subsampling
            options.InJustDecodeBounds = false;
            Bitmap image = BitmapFactory.DecodeFileDescriptor(fileDescriptor, null, options);

            parcelFileDescriptor.Close();
            return(image);
        }
Exemplo n.º 8
0
        protected async override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (resultCode == Result.Canceled && requestCode == 43)
            {
                // Notify user file picking was cancelled.
                OnDirectoryPickCancelled();
                Finish();
            }
            else
            {
                System.Diagnostics.Debug.Write(data.Data);
                try {
                    // read the file out of the cache dir
                    var    file       = new Java.IO.File(filePath);
                    var    fileLength = (int)file.Length();
                    byte[] fileBytes  = new byte[fileLength];
                    using (var inputStream = new FileInputStream(filePath))
                    {
                        await inputStream.ReadAsync(fileBytes, 0, fileLength);
                    }

                    // write the file to the path chosen by the user
                    using (var pFD = ContentResolver.OpenFileDescriptor(data.Data, "w"))
                        using (var outputSteam = new FileOutputStream(pFD.FileDescriptor))
                        {
                            outputSteam.Write(fileBytes);
                        }

                    OnDirectoryPicked(new SavePickerEventArgs(data.Data));
                } catch (Exception readEx) {
                    // Notify user file picking failed.
                    OnDirectoryPickError(readEx.Message);
                    System.Diagnostics.Debug.Write(readEx);
                } finally {
                    Finish();
                }
            }
        }
Exemplo n.º 9
0
 private Bitmap GetBitmapFromUri(AndroidUri uri)
 {
     using (var parcelFileDescriptor = ContentResolver.OpenFileDescriptor(uri, "r")) {
         return(BitmapFactory.DecodeFileDescriptor(parcelFileDescriptor.FileDescriptor));
     }
 }
Exemplo n.º 10
0
        /// <summary>
        /// Decode image from imageUri, and resize according to the expectedMaxImageSideLength
        /// If expectedMaxImageSideLength is
        ///     (1) less than or equal to 0,
        ///     (2) more than the actual max size length of the bitmap
        ///     then return the original bitmap
        /// Else, return the scaled bitmap
        /// </summary>
        /// <returns>The size limited bitmap from URI.</returns>
        /// <param name="contentResolver">Content resolver.</param>
        /// <param name="imageUri">Image URI.</param>
        /// <param name="maxImageSideLength">The maximum side length of the image to detect, to keep the size of image less than 4MB.  Resize the image if its side length is larger than the maximum.</param>
        public static Bitmap LoadSizeLimitedBitmapFromUri(this ContentResolver contentResolver, global::Android.Net.Uri imageUri, int maxImageSideLength = 1280)
        {
            try
            {
                var outPadding    = new Rect();
                int maxSideLength = 0;

                // For saving memory, only decode the image meta and get the side length.
                var options = new BitmapFactory.Options
                {
                    InJustDecodeBounds = true
                };

                using (var fileDescriptor = contentResolver.OpenFileDescriptor(imageUri, "r"))
                {
                    using (BitmapFactory.DecodeFileDescriptor(fileDescriptor.FileDescriptor, outPadding, options))
                    {
                        // Calculate shrink rate when loading the image into memory.
                        maxSideLength              = options.OutWidth > options.OutHeight ? options.OutWidth : options.OutHeight;
                        options.InSampleSize       = 1;
                        options.InSampleSize       = calculateSampleSize(maxSideLength, maxImageSideLength);
                        options.InJustDecodeBounds = false;
                    }

                    // Load the bitmap and resize it to the expected size length
                    var bitmap = BitmapFactory.DecodeFileDescriptor(fileDescriptor.FileDescriptor, outPadding, options);

                    maxSideLength = bitmap.Width > bitmap.Height ? bitmap.Width : bitmap.Height;
                    double ratio = maxImageSideLength / (double)maxSideLength;

                    if (ratio < 1)
                    {
                        var rotatedBitmap = Bitmap.CreateScaledBitmap(
                            bitmap,
                            (int)(bitmap.Width * ratio),
                            (int)(bitmap.Height * ratio),
                            false);

                        if (rotatedBitmap != bitmap)
                        {
                            bitmap.Dispose();
                            bitmap = rotatedBitmap;
                        }
                    }

                    var returnBitmap = RotateBitmap(bitmap, GetImageRotationAngle(imageUri, contentResolver));

                    //kill this bitmap if rotate created a new one
                    if (returnBitmap != bitmap)
                    {
                        bitmap.Dispose();
                    }

                    return(returnBitmap);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return(null);
            }
        }