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

Xamarin forms android image is not getting compressed

$
0
0

I'm working on xamarin forms project. I'm taking images from gallery and uploading those to server. My back-end is parse backend where we can not upload files having size more than 1MB. So, I'm trying to compress the image so that every time the image size is less than 1MB. Mentioned below is my code :-

    protected override async void OnActivityResult (int requestCode, Result resultCode, Intent intent)
        {
            if (resultCode == Result.Canceled)
                return;

    try {
        var mediafile = await intent.GetMediaFileExtraAsync (Forms.Context);

        // get byte[] from file stream
        byte[] byteData = ReadFully (mediafile.GetStream ());

        byte[] resizedImage = ResizeAndCompressImage (byteData, 60, 60, mediafile);

        var imageStream = new ByteArrayContent (resizedImage);
        imageStream.Headers.ContentDisposition = new ContentDispositionHeaderValue ("attachment") {
            FileName = Guid.NewGuid () + ".Png"
        };

        var multi = new MultipartContent ();
        multi.Add (imageStream);
        HealthcareProfessionalDataClass lDataClass = HealthcareProfessionalDataClass.Instance;
        lDataClass.Thumbnail = multi;
        App.mByteArrayOfImage = byteData;

        MessagingCenter.Send<IPictureTaker,string> (this, "picturetaken", mediafile.Path);
    } catch (InvocationTargetException e) {
        e.PrintStackTrace ();
    } catch (Java.Lang.Exception e) {
        e.PrintStackTrace ();
    }
}`

  public static byte[] ReadFully (System.IO.Stream input)
        {
            using (var ms = new MemoryStream ()) {
                input.CopyTo (ms);
                return ms.ToArray ();
            }
        }


public static byte[] ResizeAndCompressImage (byte[] imageData, float width, float height, MediaFile file)
    {
        try {
            // Load the bitmap
            var options = new BitmapFactory.Options ();
            options.InJustDecodeBounds = true;
            options.InMutable = true;
            BitmapFactory.DecodeFile (file.Path, options);
            // Calculate inSampleSize
            options.InSampleSize = calculateInSampleSize (options, (int)width, (int)height);
            // Decode bitmap with inSampleSize set
            options.InJustDecodeBounds = false;

        var originalBitMap = BitmapFactory.DecodeByteArray (imageData, 0, imageData.Length, options);

        var resizedBitMap = Bitmap.CreateScaledBitmap (originalBitMap, (int)width, (int)height, false);

        if (originalBitMap != null) {
            originalBitMap.Recycle ();
            originalBitMap = null;
        }
        using (var ms = new MemoryStream ()) {

            resizedBitMap.Compress (Bitmap.CompressFormat.Png, 0, ms);

            if (resizedBitMap != null) {
                resizedBitMap.Recycle ();
                resizedBitMap = null;
            }
            return ms.ToArray ();
        }
    } catch (Java.Lang.Exception e) {
        e.PrintStackTrace ();
        return null;
    }
}`

    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 = 16;

    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;
}`

But the problem is my image is not getting compressed.I'm not able to upload an image having size = 2MB and I want to upload images having size at-least 30 MB .

Please let me know if there's any issue in my code.


Viewing all articles
Browse latest Browse all 89864

Trending Articles



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