65.9K
CodeProject is changing. Read more.
Home

How to Crop Image into Different Size

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Aug 6, 2014

CPOL
viewsIcon

13050

downloadIcon

552

you can now crop Image with specified size equally

Introduction

as I said in previous tips , Pictures are the most used tools by developers , this time I will show you how to crop

image in different size to do a puzzle or to add a beautiful animation in the picture.

 

Using the code

The first thing you must do , is to download the WriteableBitmapExt here or you can download it from nuget on your visual studio , this dll allow you to use the Crop

To Crop Image , you must create a WriteableBitmap image

WriteableBitmap image = new WriteableBitmap(1, 1);
image = await WriteableBitmapExtensions.FromContent(image, new Uri("ms-appx:///Assets/cat.jpg", UriKind.RelativeOrAbsolute));

Then you call the Function Cropper that takes two arguments , The image and the size : 

 public static List<WriteableBitmap> Cropper(WriteableBitmap mainImage, int size)
        {
            int num1 = mainImage.PixelWidth;
            int x = Math.Abs((mainImage.PixelHeight - mainImage.PixelWidth) / 2);
            int y = Math.Abs((mainImage.PixelHeight - mainImage.PixelWidth) / 2);
            List<WriteableBitmap> list = new List<WriteableBitmap>();
            if (mainImage.PixelWidth > mainImage.PixelHeight)
            {
                num1 = mainImage.PixelHeight;
                y = 0;
            }
            else
                x = 0;
            WriteableBitmap bmp = WriteableBitmapExtensions.Crop(mainImage, x, y, num1, num1);
            int num2 = (int)Math.Sqrt((double)size);
            int num3 = num1 / num2;
            for (int index1 = 0; index1 < num2; ++index1)
            {
                for (int index2 = 0; index2 < num2; ++index2)
                {
                    WriteableBitmap writeableBitmap = WriteableBitmapExtensions.Crop(bmp, index2 * num3, index1 * num3, num3, num3);
                    list.Add(writeableBitmap);
                }
            }
            return list;
        }

This function return as well a List of WriteableBitmap.

After that you bind this List to the number of images that you create it on the XAML :


  for (int index = 0; index <= 16 - 1; ++index)
            {

   (this.GridMain.FindName("P_4_" + index.ToString()) as Image).Source = (ImageSource)wplist[(int)Convert.ToInt16(this.pictureArray[index])];
            }

History

If you are Interesting in this sample you can Download it and take the rest of the project. hope you enjoy and like it :)