Bitmapsource is the most basic type of WPF images. It also provides two pixel-related methods: copypixels and create. You can use these two methods to cut a part of an image, similar to the croppedbitmap type of another bitmapsource.
The copypixels method needs to initialize the array in advance and specify a rectangle (int32rect type) to indicate the size of the occupied area. Calculate the number of bytes (STRIDE parameter) and offset (offset parameter, usually 0) in each row of the image to call copypixels correctly. Then, use the filled array and call the create method. The other part of the cut image object is generated.
The value of the cut rectangle represents the position of the image pixel. For example, for an image of 200*200 pixels, we need the upper right corner of part 2. The rectangle is defined as new int32rect (1/4, 100 );
The size of the last filled data should not be pixels.
Define two image controls on the Interface: img1 and img2
<UniformgridRows="1">
<ImageName="Img1"/>
<ImageName="Img2"/>
</Uniformgrid>
OperationsCodeFirst, read the file and display it in img1:
// Image path
VaRPath= @ "E: \ Users \ mgen \ pictures \ mgenx.jpg";
// Create bitmapsource
BitmapsourceBitmap= New Bitmapimage(New Uri(Path,Urikind.Absolute ));
// Display the original image in img1
Img1.Source=Bitmap;
Next, copy part of the image data to the array through copypixels:
// Define the cut rectangle
VaRCut= New Int32rect(100,0,100,100);
// Calculate the stride
VaRStride=Bitmap.Format.Bitsperpixel*Cut.Width/ 8;
// Declare a byte array
Byte[] Data= New Byte[Cut.Height*Stride];
// Call copypixels
Bitmap.Copypixels (CUT, Data, stride,0);
Finally, use bitmapsource. Create to create bitmapsource and display it in the img2 control:
Img2.Source= Bitmapsource.Create (100,100,0,0,Pixelformats.Bgr32,Null, Data, stride );
Result: The Source image is displayed on the left and the upper right corner of 1/4 on the right:
Of course, the array filled with copypixels can be processed at will, for example, reversed:
For(IntI= 0; I<Data.Length; I++)
{
Data [I]=(Byte)(Byte.Maxvalue-Data [I]);
}
Run againProgram: