Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 91519

Cropping image in Android throwing out of Memory

$
0
0

I'm using the following code to crop an image in Android but whenever the image is over about size 1500x 1500 I get out of memory exceptions. I've set my max heap size to 1G, and in my manifest set the Large Heap Size to true. Any thoughts as to what else I can do?

`public class ImageCropperAndroid : IImageCropper
{
public byte[] CropPhoto(byte[] photoToCropBytes, Rectangle rectangleToCrop, double outputWidth, double outputHeight)
{
using (var photoOutputStream = new MemoryStream())
{
// Load the bitmap
var inSampleSize = CalculateInSampleSize((int)rectangleToCrop.Width, (int)rectangleToCrop.Height, (int)outputWidth, (int)outputHeight);
var options = new BitmapFactory.Options();
options.InSampleSize = inSampleSize;
//options.InPurgeable = true; see http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html
using (var photoToCropBitmap = BitmapFactory.DecodeByteArray(photoToCropBytes, 0, photoToCropBytes.Length, options))
{
var matrix = new Matrix();
var martixScale = outputWidth / rectangleToCrop.Width * inSampleSize;
matrix.PostScale((float)martixScale, (float)martixScale);
using (var photoCroppedBitmap = Bitmap.CreateBitmap(photoToCropBitmap, (int)(rectangleToCrop.X / inSampleSize), (int)(rectangleToCrop.Y / inSampleSize), (int)(rectangleToCrop.Width / inSampleSize), (int)(rectangleToCrop.Height / inSampleSize), matrix, true))
{
photoCroppedBitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, photoOutputStream);
}
}

            return photoOutputStream.ToArray();
        }
    }
    public static int CalculateInSampleSize(int inputWidth, int inputHeight, int outputWidth, int outputHeight)
    {
        //see http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

        int inSampleSize = 1;       //default

        if (inputHeight > outputHeight || inputWidth > outputWidth)
        {

            int halfHeight = inputHeight / 2;
            int halfWidth = inputWidth / 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) > outputHeight && (halfWidth / inSampleSize) > outputWidth)
            {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }`

Viewing all articles
Browse latest Browse all 91519

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>