locked
如何截取一张图片的一部分并显示? RRS feed

  • 常规讨论

  • 很多时候我们需要对图片进行操作,WinRT为我们提供了方便图片操作的类WriteableBitmap,以及用于解码以及编码的BitmapDecoderBitmapEncoder类,我们将会给出一个例子这个例子中演示了截取图片的一部分并显示:

    这里我们从(100100)截取宽度300、高度300的一部分:

    private async void getcontent()
            {
                uint startX=100;
                uint startY=100;
                uint height=300;
                uint width=300;
    
                StorageFile image1 = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///image/test1.jpg"));
                using (IRandomAccessStream stream1 = await image1.OpenAsync(FileAccessMode.Read))
                {
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream1);
    
                    byte[] pixels = await GetPixelData(decoder, startX, startY, width, height,decoder.PixelWidth,decoder.PixelHeight);
    
                    // Stream the bytes into a WriteableBitmap
                    WriteableBitmap wb = new WriteableBitmap((int)width, (int)height);
                    Stream pixStream = wb.PixelBuffer.AsStream();
                    pixStream.Write(pixels, 0, (int)(width * height * 4));
    
                    this.img.Source = wb;
    
                }
            }
    
            private static async Task<byte[]> GetPixelData(BitmapDecoder decoder, uint startPointX, uint startPointY,
            uint width, uint height, uint scaledWidth, uint scaledHeight)
            {
    
                BitmapTransform transform = new BitmapTransform();
                BitmapBounds bounds = new BitmapBounds();
                bounds.X = startPointX;
                bounds.Y = startPointY;
                bounds.Height = height;
                bounds.Width = width;
                transform.Bounds = bounds;
    
                transform.ScaledWidth = scaledWidth;
                transform.ScaledHeight = scaledHeight;
    
                // Get the cropped pixels within the bounds of transform.
                PixelDataProvider pix = await decoder.GetPixelDataAsync(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Straight,
                    transform,
                    ExifOrientationMode.IgnoreExifOrientation,
                    ColorManagementMode.ColorManageToSRgb);
                byte[] pixels = pix.DetachPixelData();
                return pixels;
            }
    

    代码参考:

    http://code.msdn.microsoft.com/windowsapps/CSWin8AppCropBitmap-52fa1ad7


    Aaron
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    2013年1月24日 4:50
    版主