Example #1
0
        protected override async void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            System.Console.WriteLine("requestCode: " + requestCode);
            System.Console.WriteLine("resultCode: " + resultCode);
            // User canceled
            if (resultCode == Result.Canceled)
            {
                return;
            }

            if (requestCode == 1)
            {
                var   fileTask = data.GetMediaFileExtraAsync(this);
                await fileTask;

                fileName      = fileTask.Result.Path;
                fileNameThumb = fileName.Replace(".jpg", "_thumb.jpg");
                System.Console.WriteLine("Image path: " + fileName);
                Bitmap b = BitmapFactory.DecodeFile(fileName);

                // Display the bitmap
                photoImageView.SetImageBitmap(b);
                // Cleanup any resources held by the MediaFile instance
                fileTask.Result.Dispose();

                b.Dispose();

                var options = new BitmapFactory.Options {
                    OutHeight = 128, OutWidth = 128
                };
                var newBitmap = await BitmapFactory.DecodeFileAsync(fileName, options);

                using (var @out = new System.IO.FileStream(fileNameThumb, System.IO.FileMode.Create)) {
                    newBitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 90, @out);
                }
                newBitmap.Dispose();
            }
        }
Example #2
0
        private Bitmap GetBitmap(string path)
        {
            var uri = GetImageUri(path);

            try
            {
                const int imageMaxSize = 1024;
                var       ins          = ContentResolver.OpenInputStream(uri);

                var o = new BitmapFactory.Options {
                    InJustDecodeBounds = true
                };

                BitmapFactory.DecodeStream(ins, null, o);
                ins.Close();

                var scale = 1;
                if (o.OutHeight > imageMaxSize || o.OutWidth > imageMaxSize)
                {
                    scale = (int)Math.Pow(2, (int)Math.Round(Math.Log(imageMaxSize / (double)Math.Max(o.OutHeight, o.OutWidth)) / Math.Log(0.5)));
                }

                var o2 = new BitmapFactory.Options {
                    InSampleSize = scale
                };
                ins = ContentResolver.OpenInputStream(uri);
                var b = BitmapFactory.DecodeStream(ins, null, o2);
                ins.Close();

                return(b);
            }
            catch (Exception e)
            {
                Log.Error(GetType().Name, e.Message);
            }

            return(null);
        }
Example #3
0
        /*
         * Method name: DisplayPicture
         * Purpose: To get and display the image
         */
        public void DisplayPicture(int requestCode, Result resultCode, Activity activity, Camera camera, Context context)
        {
            if (requestCode == _photoCode)
            {
                if (resultCode == Result.Ok)
                {
                    Console.WriteLine(Uri.Parse(camera.GetImage().AbsolutePath));
                    var options = new BitmapFactory.Options {
                        InJustDecodeBounds = true
                    };

                    var sample = 4;
                    options.InSampleSize       = sample;
                    options.InJustDecodeBounds = false;

                    using (var image = GetImage(options, camera.GetImage().AbsolutePath))
                    {
                        _imageViewer.SetImageBitmap(image);
                    }
                    _url = camera.GetImage().AbsolutePath;
                }
                else
                {
                    if (_previousActivity == "QuickMenu")
                    {
                        Toast.MakeText(context, "Back to homepage", ToastLength.Short).Show();
                        var childMenu = new Intent(context, typeof(MainActivity));
                        context.StartActivity(childMenu);
                    }
                    else
                    {
                        Toast.MakeText(context, "Back to main menu", ToastLength.Short).Show();
                        var mainMenu = new Intent(context, typeof(TeacherMainMenuActivity));
                        context.StartActivity(mainMenu);
                    }
                }
            }
        }
Example #4
0
        public static void SetTheme(this RelativeLayout layout, string background, bool isDrawable)
        {
            if (isDrawable)
            {
                BitmapFactory.Options options = new BitmapFactory.Options()
                {
                    InSampleSize = 8
                };

                var bmp = BitmapFactory.DecodeResource(_context.Resources, _theme.Images[background], options);
                using (var scaledBmp = Bitmap.CreateScaledBitmap(bmp, _context.Resources.DisplayMetrics.WidthPixels, _context.Resources.DisplayMetrics.HeightPixels - DroidDAL.AuthBackgroundHeightOffset, true))
                {
                    bmp.Recycle();
                    bmp.Dispose();

                    layout.Background = new BitmapDrawable(_context.Resources, scaledBmp);
                }
            }
            else
            {
                layout.SetBackgroundColor(_theme.Colors[background]);
            }
        }
        private static async Task <Bitmap> DecodeFromFileAsync(string path, int width, int height)
        {
            var options = new BitmapFactory.Options();

            try
            {
                options.InJustDecodeBounds = true;
                var bytes = File.ReadAllBytes(path);
                using (var ms = new MemoryStream(bytes))
                {
                    await BitmapFactory.DecodeStreamAsync(ms, null, options);

                    options.InSampleSize       = BitmapHelper.CalculateInSampleSize(options, width, height);
                    options.InJustDecodeBounds = false;
                    ms.Position = 0;
                    return(await BitmapFactory.DecodeStreamAsync(ms, null, options));
                }
            }
            catch
            {
                return(null);
            }
        }
        private int CalculateInSampleSize(BitmapFactory.Options options, int requestedWidth, int requestedHeight)
        {
            // Raw height and width

            int height       = options.OutHeight;
            int width        = options.OutWidth;
            int inSampleSize = 1;

            if (height > requestedHeight || width > requestedWidth)
            {
                // the image is bigger than we want it to be.

                int halfHeight = height / 2;
                int halfWidth  = width / 2;

                while ((halfHeight / inSampleSize) > requestedHeight && (halfWidth / inSampleSize) > requestedWidth)
                {
                    inSampleSize *= 2;
                }
            }

            return(inSampleSize);
        }
Example #7
0
        static int CalculateInSampleSize(BitmapFactory.Options options, float reqWidth, float reqHeight, bool maxResolution)
        {
            float height       = options.OutHeight;
            float width        = options.OutWidth;
            int   inSampleSize = 1;

            if (height > reqHeight || width > reqWidth)
            {
                // Calculate the largest inSampleSize value that is a power of 2 and keeps both
                // height and width larger than the requested height and width.
                while ((height / inSampleSize) > reqHeight && (width / inSampleSize) > reqWidth)
                {
                    inSampleSize *= 2;
                }

                if (maxResolution && inSampleSize > 1)
                {
                    inSampleSize /= 2;
                }
            }

            return(inSampleSize);
        }
Example #8
0
        private Bitmap compressImage(string path)
        {
            int width  = 1024;
            int height = 768;
            int scale  = 1;
            var opts   = new BitmapFactory.Options();

            opts.InJustDecodeBounds = true;
            BitmapFactory.DecodeFile(path, opts);
            if (opts.OutWidth > opts.OutHeight && opts.OutWidth > width)
            {//如果宽度大的话根据宽度固定大小缩放
                scale = (int)(opts.OutWidth / width);
            }
            else if (opts.OutWidth < opts.OutHeight && opts.OutWidth > height)
            {//如果高度高的话根据宽度固定大小缩放
                scale = (int)(opts.OutHeight / height);
            }
            opts.InJustDecodeBounds = false;
            opts.InSampleSize       = scale;
            Bitmap test = BitmapFactory.DecodeFile(path, opts);

            return(BitmapFactory.DecodeFile(path, opts));
        }
Example #9
0
        public static Bitmap LoadAndResizeBitmap(this string fileName, int width, int height)
        {
            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;
            Bitmap resizedBitmap = BitmapFactory.DecodeFile(fileName, options);

            return(resizedBitmap);
        }
        private string DownloadImage(string url)
        {
            try {
                using (var stream = new MemoryStream()) {
                    using (var imageUrl = new Java.Net.URL(url)) {
                        var options = new BitmapFactory.Options {
                            InSampleSize = 1,
                            InPurgeable  = true
                        };

                        var bit = BitmapFactory.DecodeStream(imageUrl.OpenStream(), null, options);
                        bit.Compress(Bitmap.CompressFormat.Png, 70, stream);
                    }
                    var imageBytes = stream.ToArray();

                    File.WriteAllBytes(this.Path, imageBytes);
                }
            } catch (Exception ex) {
                Log.WriteLine(LogPriority.Error, "GetImageFromBitmap Error", ex.Message);
            }

            return(this.Path);
        }
Example #11
0
        public static int CalculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
        {
            // Начальная высота и ширина изображения
            int height       = options.OutHeight;
            int width        = options.OutWidth;
            int inSampleSize = 1;

            if (height > reqHeight || width > reqWidth)
            {
                int halfHeight = height / 2;
                int halfWidth  = width / 2;

                // Рассчитываем наибольшее значение inSampleSize, которое равно степени двойки
                // и сохраняем высоту и ширину, когда они больше необходимых
                while ((halfHeight / inSampleSize) > reqHeight &&
                       (halfWidth / inSampleSize) > reqWidth)
                {
                    inSampleSize *= 2;
                }
            }

            return(inSampleSize);
        }
Example #12
0
        public byte[] ResizeImage(string sourceFile)
        {
            try
            {
                var options = new BitmapFactory.Options()
                {
                    InJustDecodeBounds = false,
                    InPurgeable        = true,
                };

                using (var image = BitmapFactory.DecodeFile(sourceFile, options))
                    using (var bitmapScaled = Bitmap.CreateScaledBitmap(image, 48, 48, true))
                        using (MemoryStream stream = new MemoryStream())
                        {
                            bitmapScaled.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
                            return(stream.ToArray());
                        }
            }
            catch
            {
                return(new byte[0]);
            }
        }
Example #13
0
        private static int CalculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
        {
            // Raw height and width of image
            int height       = options.OutHeight;
            int width        = options.OutWidth;
            int inSampleSize = 1;

            if (height > reqHeight || width > reqWidth)
            {
                int halfHeight = height / 2;
                int halfWidth  = width / 2;

                // Calculate the largest inSampleSize value that is a power of 2 and keeps both
                // height and width larger than the requested height and width.
                while ((halfHeight / inSampleSize) > reqHeight &&
                       (halfWidth / inSampleSize) > reqWidth)
                {
                    inSampleSize *= 2;
                }
            }

            return(inSampleSize);
        }
Example #14
0
        public static int CalculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
        {
            // Raw height and width of image
            int height       = options.OutHeight;
            int width        = options.OutWidth;
            int inSampleSize = 1;

            if (height > reqHeight || width > reqWidth)
            {
                // Calculate ratios of height and width to requested height and
                // width
                int heightRatio = height / reqHeight;
                int widthRatio  = width / reqWidth;

                // Choose the smallest ratio as inSampleSize value, this will
                // guarantee
                // a final image with both dimensions larger than or equal to the
                // requested height and width.
                inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
            }

            return(inSampleSize);
        }
Example #15
0
        private static int GetInSampleSize(
            BitmapFactory.Options options,
            int requiredWidth,
            int requiredHeight)
        {
            var height       = options.OutHeight;
            var width        = options.OutWidth;
            var inSampleSize = 1;

            if (height > requiredHeight || width > requiredWidth)
            {
                var halfHeight = height / 2;
                var halfWidth  = width / 2;

                while ((halfHeight / inSampleSize) >= requiredHeight &&
                       (halfWidth / inSampleSize) >= requiredWidth)
                {
                    inSampleSize *= 2;
                }
            }

            return(inSampleSize);
        }
Example #16
0
        public async Task <bool> LoadThumbnail(Context context)
        {
            BitmapFactory.Options Opts = new BitmapFactory.Options
            {
                InSampleSize = 2
            };
            FileInfo imgFile = new FileInfo($"{context.GetExternalFilesDir(null)}/images/{Attachment.ID}{Attachment.Extension}");

            if (imgFile.Exists)
            {
                var bmp = await BitmapFactory.DecodeFileAsync(imgFile.FullName, Opts);

                if (bmp != null)
                {
                    Thumbnail = bmp.ToRoundedCornerBitmap(12);
                }
            }
            else
            {
                Thumbnail = null;
            }
            return(Thumbnail != null);
        }
Example #17
0
        public static async Task <IFormsAnimationDrawable> LoadImageAnimationAsync(FileImageSource imagesource, Context context, CancellationToken cancelationToken = default(CancellationToken))
        {
            string file = ((FileImageSource)imagesource).File;
            FormsAnimationDrawable animation = null;

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

            int drawableIdentifier = context.GetDrawableId(file);

            if (drawableIdentifier != 0)
            {
                if (!FileImageSourceHandler.DecodeSynchronously)
                {
                    await BitmapFactory.DecodeResourceAsync(context.Resources, drawableIdentifier, options);
                }
                else
                {
                    BitmapFactory.DecodeResource(context.Resources, drawableIdentifier, options);
                }

                animation = await GetFormsAnimationDrawableFromResource(drawableIdentifier, context, options);
            }
            else
            {
                animation = await GetFormsAnimationDrawableFromFile(file, context, options);
            }

            if (animation == null)
            {
                Application.Current?.FindMauiContext()?.CreateLogger <FileImageSourceHandler>()?.LogWarning("Could not retrieve image or image data was invalid: {imagesource}", imagesource);
            }

            return(animation);
        }
Example #18
0
        public static Bitmap LoadAndResizeBitmap2(Bitmap bitmapp, int width, int height)
        {
            byte[] fileByte;
            using (var stream = new MemoryStream())
            {
                bitmapp.Compress(Bitmap.CompressFormat.Png, 0, stream);
                fileByte = stream.ToArray();
            }

            BitmapFactory.Options options = new BitmapFactory.Options {
                InJustDecodeBounds = true
            };
            BitmapFactory.DecodeByteArray(fileByte, 0, fileByte.Length, 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;
            Bitmap resizedBitmap = BitmapFactory.DecodeByteArray(fileByte, 0, fileByte.Length, options);

            using (MemoryStream ms = new MemoryStream())
            {
                resizedBitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, ms);
            }

            return(resizedBitmap);
        }
Example #19
0
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            View           grid;
            LayoutInflater inflater = (LayoutInflater)mContext
                                      .GetSystemService(Context.LayoutInflaterService);


            grid = new View(mContext);
            grid = inflater.Inflate(Resource.Layout.grid_layout, null);
            TextView  textView  = (TextView)grid.FindViewById(Resource.Id.grid_text);
            ImageView imageView = (ImageView)grid.FindViewById(Resource.Id.grid_image);



            BitmapFactory.Options bmOptions = new BitmapFactory.Options();
            bmOptions.InJustDecodeBounds = false;
            bmOptions.InSampleSize       = 4;
            bmOptions.InPurgeable        = true;
            Bitmap bitmap = BitmapFactory.DecodeFile(myList[position].ImagePath, bmOptions);

            imageView.SetImageBitmap(bitmap);


            if (convertView != null)
            {
                if (myList[position].Status.Equals("1"))
                {
                    imageView.SetBackgroundColor(Android.Graphics.Color.AntiqueWhite);// this is a selected position so make it red
                }
                else
                {
                    imageView.SetBackgroundColor(Android.Graphics.Color.White); //default color
                }
            }

            return(grid);
        }
Example #20
0
        public static Bitmap LoadAndResizeBitmap(string fileName, int width, int height)
        {
            // First we get the the dimensions of the file on disk
            BitmapFactory.Options options = new BitmapFactory.Options {
                InJustDecodeBounds = true
            };
            BitmapFactory.DecodeFile(fileName, options);

            //ExifInterface exif = new ExifInterface(fileName);
            //var orientation = exif.GetAttributeInt(ExifInterface.TagOrientation, 1);

            //if (orientation == )
            //{
            //    Matrix matrix = new Matrix();
            //    matrix.PostRotate(90);
            //}

            // 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 > height || outWidth > width)
            {
                inSampleSize = outWidth > outHeight
                                   ? outHeight / height
                                   : outWidth / width;
            }

            // Now we will load the image and have BitmapFactory resize it for us.
            options.InSampleSize       = inSampleSize;
            options.InJustDecodeBounds = false;
            Bitmap resizedBitmap = BitmapFactory.DecodeFile(fileName, options);

            return(resizedBitmap);
        }
Example #21
0
        public static async Task <IFormsAnimationDrawable> LoadImageAnimationAsync(FileImageSource imagesource, Context context, CancellationToken cancelationToken = default(CancellationToken))
        {
            string file = ((FileImageSource)imagesource).File;
            FormsAnimationDrawable animation = null;

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

            int drawableIdentifier = ResourceManager.GetDrawableByName(file);

            if (drawableIdentifier != 0)
            {
                if (!FileImageSourceHandler.DecodeSynchronously)
                {
                    await BitmapFactory.DecodeResourceAsync(context.Resources, drawableIdentifier, options);
                }
                else
                {
                    BitmapFactory.DecodeResource(context.Resources, drawableIdentifier, options);
                }

                animation = await GetFormsAnimationDrawableFromResource(drawableIdentifier, context, options);
            }
            else
            {
                animation = await GetFormsAnimationDrawableFromFile(file, context, options);
            }

            if (animation == null)
            {
                Internals.Log.Warning(nameof(FileImageSourceHandler), "Could not retrieve image or image data was invalid: {0}", imagesource);
            }

            return(animation);
        }
        // http://www.united-bears.co.jp/blog/archives/909
        public byte[] ShrinkImage(Stream fileStream, float minSize)
        {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.InJustDecodeBounds = true;
            BitmapFactory.DecodeStream(fileStream, null, options);
            fileStream.Position = 0;

            float desireWidth, desireHeight;

            if (options.OutWidth > options.OutHeight)
            {
                desireHeight = minSize;
                desireWidth  = options.OutWidth * desireHeight / options.OutHeight;
            }
            else
            {
                desireWidth  = minSize;
                desireHeight = options.OutHeight * desireWidth / options.OutWidth;
            }

            float scaleX = options.OutWidth / desireWidth;
            float scaleY = options.OutHeight / desireHeight;

            options.InSampleSize       = (int)Math.Floor(Math.Max(scaleX, scaleY));
            options.InJustDecodeBounds = false;

            byte[] byteArray;

            using (Bitmap bitmap = BitmapFactory.DecodeStream(fileStream, null, options))
                using (MemoryStream ms = new MemoryStream())
                {
                    bitmap.Compress(Bitmap.CompressFormat.Png, 80, ms);
                    byteArray = ms.ToArray();
                }

            return(byteArray);
        }
Example #23
0
        public Bitmap GetBitmapFromReusableSet(BitmapFactory.Options options)
        {
            Bitmap bitmap = null;

            var bitmapToRemove = new List <SoftReference>();

            if (_reusableBitmaps != null && !_reusableBitmaps.IsEmpty)
            {
                foreach (var softReference in _reusableBitmaps)
                {
                    var item = softReference.Get() as Bitmap;
                    if (item != null && item.IsMutable)
                    {
                        if (CanUseForInBitmap(item, options))
                        {
                            bitmap = item;
                            bitmapToRemove.Add(softReference);
                            break;
                        }
                    }
                    else
                    {
                        bitmapToRemove.Add(softReference);
                    }
                }
            }

            if (_reusableBitmaps != null && bitmapToRemove.Count > 0)
            {
                foreach (var i in bitmapToRemove)
                {
                    _reusableBitmaps.TryRemove(i);
                }
            }

            return(bitmap);
        }
Example #24
0
        public byte[] ResizeImage(byte[] imageData, float width, float height)
        {
            // Load the bitmap
            BitmapFactory.Options options = new BitmapFactory.Options(); // Create object of bitmapfactory's option method for further option use
            options.InPurgeable = true;                                  // inPurgeable is used to free up memory while required
            Bitmap originalImage = BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length, options);

            float newHeight = 0;
            float newWidth  = 0;

            var originalHeight = originalImage.Height;
            var originalWidth  = originalImage.Width;

            if (originalHeight > originalWidth)
            {
                newHeight = height;
                float ratio = originalHeight / height;
                newWidth = originalWidth / ratio;
            }
            else
            {
                newWidth = width;
                float ratio = originalWidth / width;
                newHeight = originalHeight / ratio;
            }

            Bitmap resizedImage = Bitmap.CreateScaledBitmap(originalImage, (int)newWidth, (int)newHeight, true);

            originalImage.Recycle();

            using (MemoryStream ms = new MemoryStream())
            {
                resizedImage.Compress(Bitmap.CompressFormat.Png, 100, ms);
                resizedImage.Recycle();
                return(ms.ToArray());
            }
        }
        private void GetBitmap()
        {
            var uri = Android.Net.Uri.FromFile(file);

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.InJustDecodeBounds = true;
            BitmapFactory.DecodeFile(file.Path, options);
            int imageWidth  = options.OutWidth;
            int imageHeight = options.OutHeight;
            int viewWidth   = imageV1.Width;
            int viewHeight  = imageV1.Height;
            int scale       = 1;

            if (imageHeight > viewHeight || imageWidth > viewWidth)
            {
                if (imageWidth > imageHeight)
                {
                    scale = imageHeight / viewHeight;
                }
                else
                {
                    scale = imageWidth / viewWidth;
                }
            }
            options.InJustDecodeBounds = false;
            options.InSampleSize       = scale;

            using (Bitmap bitmap = BitmapFactory.DecodeFile(file.Path))
            {
                Matrix matrix = new Matrix();
                matrix.PostRotate(0);
                using (Bitmap bitmapRotate = Bitmap.CreateBitmap(bitmap, 0, 0, bitmap.Width, bitmap.Height, matrix, true))
                {
                    imageV1.SetImageBitmap(bitmapRotate);
                }
            }
        }
Example #26
0
        public static async void SaveSmallBitmapAsJPG()
        {
            //http://stackoverflow.com/questions/477572/strange-out-of-memory-issue-while-loading-an-image-to-a-bitmap-object/823966#823966

            //  var path = new File(
            //                Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures), "OCR").AbsolutePath;
            //   var smallfilePath = System.IO.Path.Combine(path, "small.jpg");
            //   var bigfilePath = System.IO.Path.Combine(path, "OCR.jpg");

            BitmapFactory.Options opts = new BitmapFactory.Options();

            // load the image and have BitmapFactory resize it for us.
            opts.InSampleSize       = 4;     //  1/4 size
            opts.InJustDecodeBounds = false; //set to false to get the whole image not just the bounds
            Bitmap bitmap = await BitmapFactory.DecodeFileAsync(AppPath.bigfilePath(), opts);


            //rotate a bmp
            Matrix matrix = new Matrix();

            matrix.PostRotate(90);
            var rotatedBitmap = Bitmap.CreateBitmap(bitmap, 0, 0, bitmap.Width, bitmap.Height, matrix, true);


            //write it back
            using (var stream = new FileStream(AppPath.smallfilePath(), FileMode.Create))
            {
                await rotatedBitmap.CompressAsync(Bitmap.CompressFormat.Jpeg, 70, stream);//70% compressed

                stream.Close();
            }

            //    await stream.FlushAsync();
            // Free the native object associated with this bitmap, and clear the reference to the pixel data. This will not free the pixel data synchronously; it simply allows it to be garbage collected if there are no other references. The bitmap is marked as "dead", meaning it will throw an exception if getPixels() or setPixels() is called, and will draw nothing.
            //  bitmap.Recycle();
            //     GC.Collect();
        }
        /// <summary>
        /// Creates the compressed image data from bitmap.
        /// </summary>
        /// <returns>The compressed image data from bitmap.</returns>
        /// <param name="url">URL.</param>
        private static byte[] CreateCompressedImageDataFromBitmap(string url)
        {
            BitmapFactory.Options options = new BitmapFactory.Options();
            // This makes sure bitmap is not loaded into memory
            options.InJustDecodeBounds = true;
            // Then get the properties of the bitmap
            BitmapFactory.DecodeFile(url, options);
            // CalculateInSampleSize calculates the right aspect ratio for the picture and then calculate
            // the factor where it will be downsampled with.
            options.InSampleSize = BitmapHelpers.CalculateInSampleSize(options, 1600, 1200);
            // Now that we know the downsampling factor, the right sized bitmap is loaded into memory.
            // So we set the InJustDecodeBounds to false because we now know the exact dimensions.
            options.InJustDecodeBounds = false;

            // Now we are loading it with the correct options. And saving precious memory.
            Bitmap bm = BitmapFactory.DecodeFile(url, options);

            // Convert it to Base64 by first converting the bitmap to
            // a byte array. Then convert the byte array to a Base64 String.
            var stream = new MemoryStream();

            bm.Compress(Bitmap.CompressFormat.Jpeg, 80, stream);
            return(stream.ToArray());
        }
Example #28
0
        void AddInBitmapOptions(BitmapFactory.Options options)
        {
            // inBitmap only works with mutable bitmaps so force the decoder to
            // return mutable bitmaps.
            options.InMutable = true;

            // Try and find a bitmap to use for inBitmap
            ISelfDisposingBitmapDrawable bitmapDrawable = null;

            try
            {
                bitmapDrawable = ImageCache.Instance.GetBitmapDrawableFromReusableSet(options);
                var bitmap = bitmapDrawable == null ? null : bitmapDrawable.Bitmap;

                if (bitmap != null && bitmap.Handle != IntPtr.Zero && !bitmap.IsRecycled)
                {
                    options.InBitmap = bitmapDrawable.Bitmap;
                }
            }
            finally
            {
                bitmapDrawable?.SetIsRetained(false);
            }
        }
Example #29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AndroidSurfaceSource"/> class.
        /// </summary>
        /// <param name="stream">The <see cref="Stream"/> that contains the surface data.</param>
        public AndroidSurfaceSource(Stream stream)
        {
            Contract.Require(stream, nameof(stream));

            var opts = new BitmapFactory.Options();

            opts.InPreferredConfig = Bitmap.Config.Argb8888;

            using (var bmp = BitmapFactory.DecodeStream(stream, new Rect(), opts))
            {
                this.width  = bmp.Width;
                this.height = bmp.Height;
                this.stride = bmp.RowBytes;

                this.bmpData       = new Byte[stride * height];
                this.bmpDataHandle = GCHandle.Alloc(bmpData, GCHandleType.Pinned);

                var pixels = bmp.LockPixels();

                Marshal.Copy(pixels, bmpData, 0, bmpData.Length);

                bmp.UnlockPixels();
            }
        }
Example #30
0
        public static Bitmap LoadAndResizeBitmap(this string filename, int width, int height)
        {
            System.Diagnostics.Debug.WriteLine("BitmapHelpers.LoadAndResizeBitmap()");
            System.Diagnostics.Debug.WriteLine("Filename: " + filename);
            System.Diagnostics.Debug.WriteLine("Width: " + width);
            System.Diagnostics.Debug.WriteLine("Height: " + height);

            // First we get the the dimensions of the file on disk
            BitmapFactory.Options options = new BitmapFactory.Options {
                InJustDecodeBounds = true
            };
            BitmapFactory.DecodeFile(filename, 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;

            System.Diagnostics.Debug.WriteLine("outWidth: " + outWidth);
            System.Diagnostics.Debug.WriteLine("outHeight: " + outHeight);

            if (outHeight > height || outWidth > width)
            {
                inSampleSize = outWidth > outHeight
                                   ? outHeight / height
                                   : outWidth / width;
            }

            // Now we will load the image and have BitmapFactory resize it for us.
            options.InSampleSize       = inSampleSize;
            options.InJustDecodeBounds = false;
            Bitmap resizedBitmap = BitmapFactory.DecodeFile(filename, options);

            return(resizedBitmap);
        }
	  /// <summary>
	  /// Decode downloaded big picture. </summary>
	  /// <param name="context"> any application context. </param>
	  /// <param name="downloadId"> downloaded picture identifier. </param>
	  /// <returns> decoded bitmap if successful, null on error. </returns>
	  public static Bitmap getBigPicture(Context context, long downloadId)
	  {
		/* Decode bitmap */
		System.IO.Stream stream = null;
		try
		{
		  /*
		   * Query download manager to get file. FIXME For an unknown reason, using the file descriptor
		   * fails after APK build with ProGuard, we use stream instead.
		   */
		  DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
		  Uri uri = downloadManager.getUriForDownloadedFile(downloadId);
		  ContentResolver contentResolver = context.ContentResolver;
		  stream = contentResolver.openInputStream(uri);

		  /*
		   * Bitmaps larger than 2048 in any dimension are likely to cause OutOfMemoryError in the
		   * NotificationManager or even here. Plus some devices simply don't accept such images: the
		   * notification manager can drop the notification without any way to check that via API. To
		   * avoid the problem, sub sample the image in an efficient way (not using Bitmap matrix
		   * scaling after decoding the bitmap with original size: it could run out of memory when
		   * decoding the full image). FIXME There is center cropping applied by the NotificationManager
		   * on the bitmap we provide, we can't avoid it, see
		   * https://code.google.com/p/android/issues/detail?id=58318.
		   */
		  BitmapFactory.Options options = new BitmapFactory.Options();
		  options.inJustDecodeBounds = true;
		  options.inSampleSize = 1;
		  options.inPreferQualityOverSpeed = true;

		  /* Decode dimensions */
		  BitmapFactory.decodeStream(stream, null, options);
		  int maxDim = Math.Max(options.outWidth, options.outHeight);

		  /* Compute sub sample size (it must be a power of 2) */
		  while (maxDim > 2048)
		  {
			options.inSampleSize <<= 1;
			maxDim >>= 1;
		  }

		  /* Decode actual bitmap */
		  options.inJustDecodeBounds = false;
		  stream.Close();
		  stream = contentResolver.openInputStream(uri);
		  return BitmapFactory.decodeStream(stream, null, options);
		}
		catch (Exception)
		{
		  /* Abort, causes are likely FileNotFoundException or OutOfMemoryError */
		  return null;
		}
		finally
		{
		  /* Silently close stream */
		  if (stream != null)
		  {
			try
			{
			  stream.Close();
			}
			catch (IOException)
			{
			}
		  }
		}
	  }
		private Bitmap decodeToBitmap(ByteBuffer jpegData, int sampleSize, int cropWidth)
		{
			sbyte[] jpegDataArray = new sbyte[jpegData.remaining()];
			jpegData.get(jpegDataArray);
			jpegData.rewind();

			BitmapFactory.Options option = new BitmapFactory.Options();
			option.inSampleSize = sampleSize;

			if (cropWidth == 0)
			{
				return BitmapFactory.decodeByteArray(jpegDataArray, 0, jpegDataArray.Length, option);
			}

			Bitmap bitmap = null;
			try
			{
				BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(jpegDataArray, 0, jpegDataArray.Length, true);

				int cropHeight = cropWidth * decoder.Height / decoder.Width;
				Rect cropRect = new Rect(decoder.Width / 2 - cropWidth, decoder.Height / 2 - cropHeight, decoder.Width / 2 + cropWidth, decoder.Height / 2 + cropHeight);

				bitmap = decoder.decodeRegion(cropRect, option);
			}
			catch (IOException e)
			{
				Console.WriteLine(e.ToString());
				Console.Write(e.StackTrace);
			}

			return bitmap;
		}
		public override void onActivityResult(int requestCode, int resultCode, Intent data)
		{
			base.onActivityResult(requestCode, resultCode, data);

			if (requestCode == REQUEST_CODE_ACTION_PICK)
			{
				if (data != null)
				{
					Uri uri = data.Data;
					System.IO.Stream @is = null;
					try
					{
						@is = ContentResolver.openInputStream(uri);
					}
					catch (FileNotFoundException e)
					{
						Console.WriteLine(e.ToString());
						Console.Write(e.StackTrace);
						return;
					}

					BitmapFactory.Options opts = new BitmapFactory.Options();
					opts.inJustDecodeBounds = false;
					opts.inSampleSize = 1;
					opts.inPreferredConfig = Bitmap.Config.RGB_565;
					Bitmap bm = BitmapFactory.decodeStream(@is, null, opts);
					mImageView.ImageBitmap = bm;

					ContentResolver cr = ContentResolver;
					Cursor c = cr.query(uri, new string[] {MediaStore.Images.Media.DATA}, null, null, null);
					if (c == null || c.Count == 0)
					{
						return;
					}
					c.moveToFirst();
					int columnIndex = c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					string text = c.getString(columnIndex);
					mTextView.Text = text;
				}
			}
		}
		private void pullDownscaledImg(string path, int width, int height)
		{
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final android.graphics.BitmapFactory.Options opt = new android.graphics.BitmapFactory.Options();
			BitmapFactory.Options opt = new BitmapFactory.Options();
			opt.inScaled = false;
			opt.inSampleSize = 4; // logic based on original and requested size.
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final android.graphics.Bitmap scaledbitmap = android.graphics.Bitmap.createScaledBitmap(android.graphics.BitmapFactory.decodeFile(path, opt), width, height, false);
			Bitmap scaledbitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(path, opt), width, height, false);
			if (scaledbitmap != null)
			{
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.io.ByteArrayOutputStream stream = new java.io.ByteArrayOutputStream();
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				scaledbitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
				mImgData = Base64.encodeToString(stream.toByteArray(), Base64.NO_WRAP);
				try
				{
					stream.close();
				}
//JAVA TO C# CONVERTER WARNING: 'final' catch parameters are not available in C#:
//ORIGINAL LINE: catch (final java.io.IOException e)
				catch (IOException e)
				{
					Console.WriteLine(e.ToString());
					Console.Write(e.StackTrace);
				}
			}
			mResult = "success"; // success
			mReason = REASON_OK; // ok
		}
		// Check whether valid image file or not
		public static bool isValidImagePath(string strImagePath)
		{
			if (strImagePath == null)
			{
				return false;
			}
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(strImagePath, options);

			return (options.outMimeType != null);
		}
		/// <summary>
		///**************************************************************************************************************
		/// Get the option for obtain the image size of bitmap.
		/// Parameter :
		/// - context : Context
		/// - uri : Image URI
		/// - bContentStreamImage : Gallery contents stream file(true)/File path(false)
		/// Return :
		/// - BitmapFactory.Options
		/// </summary>
		public static BitmapFactory.Options getBitmapSize(string strImagePath)
		{
			// ==========================================
			// Load the temporary bitmap for getting size.
			// ==========================================
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			// Bitmap photo = BitmapFactory.decodeFile(strPath, options);
			BitmapFactory.decodeFile(strImagePath, options);

			return options;
		}
Example #37
0
		private Bitmap decodeToBitmap(ByteBuffer jpegData, int sampleSize)
		{
			sbyte[] jpegDataArray = new sbyte[jpegData.remaining()];
			jpegData.get(jpegDataArray);
			jpegData.rewind();

			BitmapFactory.Options option = new BitmapFactory.Options();
			option.inSampleSize = sampleSize;

			return BitmapFactory.decodeByteArray(jpegDataArray, 0, jpegDataArray.Length, option);
		}
		/// <summary>
		/// display an image file.
		/// </summary>
		private bool setImageView(ImageView imageview, string filepath)
		{

			bool bSCameraFilterSupported = true;

			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(filepath, options);

			int photoWidth = options.outWidth;
			int photoHeight = options.outHeight;

			int targetWidth = photoWidth;
			int targetHeight = photoHeight;

			int photoSize = (photoWidth > photoHeight) ? photoWidth : photoHeight;

			if (photoSize > MAX_IMAGE_SIZE)
			{
				bSCameraFilterSupported = false;
				return bSCameraFilterSupported;
			}

			if (photoSize > 1920)
			{
				int scale = (photoSize / 1920) + 1;
				targetWidth = photoWidth / scale;
				targetHeight = photoHeight / scale;
			}

			int scaleFactor = Math.Min(photoWidth / targetWidth, photoHeight / targetHeight);

			options.inJustDecodeBounds = false;
			options.inDither = false;
			options.inSampleSize = scaleFactor;
			Bitmap orgImage = BitmapFactory.decodeFile(filepath, options);
			imageview.ImageBitmap = orgImage;

			return bSCameraFilterSupported;
		}