writablebitmap aspect ratio save image

234 views Asked by At

i'm read a image from PhotoChooserTask and have a stream of a photo. I have to reduce the size of image

i write this code

            WriteableBitmap writeableBitmap = new WriteableBitmap(400, 400);
            writeableBitmap.LoadJpeg(stream);

            using (var isoFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (isoFile.FileExists("Myfile.jpg")) isoFile.DeleteFile("Myfile.jpg");
                using (var filestream = isoFile.CreateFile("Myfile.jpg"))
                {
                    writeableBitmap.SaveJpeg(filestream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 100);
                }
            }

this code not keep aspect ration of image.

how to make?

2

There are 2 answers

2
Ertay Shashko On

First load the source image to writeableBitmap (without resizing).

Then get the source width (PixelWidth) and full height (PixelHeight). Dividing PixelWidth with PixelHeight will give you the ratio. You can use this value when resizing.

So:

float aspectRatio = (float) writeableBitmap.PixelWidth / writeableBitmap.PixelHeight;

Then when saving just do

writeableBitmap.SaveJpeg(filestream, ResizedWidthValue, (int) ResizedWidthValue / aspectRatio, 0, 100);
0
John Brush On

@ertay

i'm write this code

using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    WriteableBitmap wb = BitmapFactory.New(0, 0);
                    wb.FromStream(isolatedStorage.OpenFile("1.jpg", FileMode.Open, FileAccess.Read));

                    IsolatedStorageFileStream fileStream= isolatedStorage.CreateFile("1_thumb.jpg");

                    float aspectRatio = (float)wb.PixelWidth / wb.PixelHeight;

                    wb.SaveJpeg(fileStream, 200, (int) (200 / aspectRatio), 0, 100);

                    fileStream.Close();
                    wb = null;

                }

but wb.PixelWidth and wb.PixelHeight = 0!!

Why?