Forum Xamarin.Forms

Image Scaling

Hi,

so I have multiple Images in Drawable folder. I want to Scale some of them to smaller sizes insted of saving multiple versions of same image in my folder. Is there a way that I can for example get to my Image from Drawable, resize it and put it as a pin on a map?

Answers

  • JarvanJarvan Member, Xamarin Team Xamurai
    edited September 2019

    You can resize the image on platform projects and use DependencyService the call the method.

    public class MediaService : IMediaService
    {
    
        public byte[] ResizeImage(byte[] imageData, float width, float height)
        {
            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();
            }
    
        }
    

    Check the link:
    https://forums.xamarin.com/discussion/67531/how-to-resize-image-file-on-xamarin-forms-writeablebitmap-package-cant-be-added

Sign In or Register to comment.