Resize Image - CSharp System.Drawing

CSharp examples for System.Drawing:Image Size

Description

Resize Image

Demo Code


using Windows.Storage.Streams;
using Windows.Storage;
using Windows.Graphics.Imaging;
using System.Threading.Tasks;
using System;/*  w  w  w .j a v  a 2 s .  c  o m*/
using JP.Utils.Debug;

public class Main{

        public static async Task<IRandomAccessStream> ResizeImage(IRandomAccessStream sourceStream,uint scaleLong)
        {
            try
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);
                uint height = decoder.PixelHeight;
                uint weight = decoder.PixelWidth;

                double rate;
                uint destHeight = height;
                uint destWeight = weight;

                if (weight > height)
                {
                    rate = scaleLong / (double)weight;
                    destHeight = weight > scaleLong ? (uint)(rate * height) : height;
                    destWeight = scaleLong;
                }
                else
                {
                    rate = scaleLong / (double)height;
                    destWeight = height > scaleLong ? (uint)(rate * weight) : weight;
                    destHeight = scaleLong;
                }

                BitmapTransform transform = new BitmapTransform()
                {
                    ScaledWidth = destWeight,
                    ScaledHeight = destHeight
                };

                PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                    BitmapPixelFormat.Rgba8,
                    BitmapAlphaMode.Straight,
                    transform,
                    ExifOrientationMode.IgnoreExifOrientation,
                    ColorManagementMode.DoNotColorManage);

                var folder = ApplicationData.Current.TemporaryFolder;
                var tempfile = await folder.CreateFileAsync("temp.jpg", CreationCollisionOption.GenerateUniqueName);
                IRandomAccessStream destStream = await tempfile.OpenAsync(FileAccessMode.ReadWrite);

                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destStream);
                encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform.ScaledWidth, transform.ScaledHeight, 100, 100, pixelData.DetachPixelData());
                await encoder.FlushAsync();

                //REMEMBER
                destStream.Seek(0);

                await tempfile.DeleteAsync(StorageDeleteOption.PermanentDelete);

                return destStream;
            }
            catch(Exception e)
            {
                var task = ExceptionHelper.WriteRecordAsync(e, nameof(BitmapHandleHelper), nameof(ResizeImage));
                return null;
            }
        }
}

Related Tutorials