how to reduce the size of an image for uploAD

rick ruhl 61 Reputation points
2023-05-22T23:55:52.0466667+00:00

I used to be able to do this



*
                       file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
                        {
                            AllowCropping = false,
                            SaveMetaData = true,

#if __ANDROID__
                        DefaultCamera = CameraDevice.Front,
#else
                            DefaultCamera = CameraDevice.Rear,

#endif

                            PhotoSize = PhotoSize.Small

                        });
*/

Now I do this and it does not shrink the size of the image on the phone.

async Task TakePhotoAsync()
        {
            try
            {
                //
               var photo = await MediaPicker.CapturePhotoAsync();
                /* var photo=  DeviceInfo.Platform.Equals(DevicePlatform.iOS) && _iOSCamera != null
                     ? await _iOSCamera.CapturePhotoAsync()
                     : await MediaPicker.CapturePhotoAsync();
        
                */

#if __IOS__
                if (photo == null)
                {
                    return;
                }
                Stream stream = await photo.OpenReadAsync();

               

                SKBitmap photoBitmap = RotateBitmap(SKBitmap.Decode(stream));
                sourceStream = SKImage.FromBitmap(photoBitmap).Encode().AsStream();
#else
                await LoadPhotoAsync(photo);
#endif

                Console.WriteLine($"CapturePhotoAsync COMPLETED: {PhotoPath}");
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                // Feature is not supported on the device
            }
            catch (PermissionException pEx)
            {
                // Permissions not granted
            }
            catch (Exception ex)
            {
                Console.WriteLine($"CapturePhotoAsync THREW: {ex.Message}");
            }
        }

private byte[] ImageSourceToByteArray(ImageSource source)
        {
            byte[] resizedImage;
            StreamImageSource streamImageSource = (StreamImageSource)source;
            System.Threading.CancellationToken cancellationToken = System.Threading.CancellationToken.None;
            Task<Stream> task = streamImageSource.Stream(cancellationToken);
            Stream stream = task.Result;

            byte[] b;
            using (MemoryStream ms = new MemoryStream())
            {
                stream.CopyTo(ms);
                b = ms.ToArray();
            }

           return resizedImage = ResizeImageIOS(b, 400, 400);
            //return ImageSource.FromStream(() => new MemoryStream(resizedImage));
        }

        public static byte[] ResizeImageIOS(byte[] imageData, float width, float height)
        {
            UIImage originalImage = ImageFromByteArray(imageData);
            UIImageOrientation orientation = originalImage.Orientation;

            //create a 24bit RGB image
            using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero,
                                                 (int)width, (int)height, 8,
                                                 4 * (int)width, CGColorSpace.CreateDeviceRGB(),
                                                 CGImageAlphaInfo.PremultipliedFirst))
            {

                RectangleF imageRect = new RectangleF(0, 0, width, height);

                // draw the image
                context.DrawImage(imageRect, originalImage.CGImage);

                UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage(), 0, orientation);

                // save the image as a jpeg
                return resizedImage.AsJPEG().ToArray();
            }
        }

 	 SKBitmap RotateBitmap(SKBitmap bitmap)
        {
            SKSizeI sk = new SKSizeI(400, 400);
            SKBitmap rotatedBitmap = new SKBitmap(bitmap.Height, bitmap.Width);
            using (var surface = new SKCanvas(rotatedBitmap))
            {
                surface.Translate(rotatedBitmap.Width, 0);
                surface.RotateDegrees(90);
                surface.DrawBitmap(bitmap, 0, 0);
            }

            var dstInfo = new SKImageInfo(200, 200);
            rotatedBitmap.Resize(dstInfo, SKFilterQuality.High);
            return rotatedBitmap;
        }

Thoughts?

Developer technologies .NET Xamarin
{count} votes

Accepted answer
  1. Anonymous
    2023-05-26T02:51:32.45+00:00

    Looking into the ResizeImageIOS method, there is an UIImage.AsJPEG method. You could pass a nfloat which means compressionQuality to it , such as resizedImage.AsJPEG(0.3f). The compression quality to use, 0.0 is the maximun compression (worse quality), and 1.0 minimum compression (best quality).For more details, you could refer to AsJPEG(nfloat).

    For Android, that's Bitmap.Compress method, you could also put quality int to it. For more info, you could refer to Bitmap.Compress(Bitmap+CompressFormat, Int32, Stream) Method.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.