3

Я пишу приложение Windows Phone 8.1 (WINRT). Я использую fileopenpicker, чтобы выбрать картинку из галереи, а затем я отображу ее в своем приложении. Но я хочу, чтобы этот пользователь мог обрезать это изображение, прежде чем отображаться в приложении.WriteableBitmap.Pixels в Windows Phone 8.1

В телефоне с телефоном 8 мы использовали Задача Photochooser с параметрами ширины и возможностью обрезки, которые автоматически используются.

Теперь я пытаюсь использовать это: Windows Phone 8.0: Image Crop With Rectangle

Но нет WriteableBitmap.Pixels в Windows Phone 8,1. Что использовать вместо WriteableBitmap.Pixels?

// Create a new WriteableBitmap. The size of the bitmap is the size of the cropping rectangle 
// drawn by the user, multiplied by the image size ratio. 
WB_CroppedImage = new WriteableBitmap((int)(widthRatio * Math.Abs(Point2.X - Point1.X)), (int)(heightRatio * Math.Abs(Point2.Y - Point1.Y))); 

// Calculate the offset of the cropped image. This is the distance, in pixels, to the top left corner 
// of the cropping rectangle, multiplied by the image size ratio. 
int xoffset = (int)(((Point1.X < Point2.X) ? Point1.X : Point2.X) * widthRatio); 
int yoffset = (int)(((Point1.Y < Point2.Y) ? Point1.Y : Point2.X) * heightRatio); 

// Copy the pixels from the targeted region of the source image into the target image, 
// using the calculated offset 
if (WB_CroppedImage.Pixels.Length > 0) 
{ 
    for (int i = 0; i < WB_CroppedImage.Pixels.Length; i++) 
    { 
     int x = (int)((i % WB_CroppedImage.PixelWidth) + xoffset); 
     int y = (int)((i/WB_CroppedImage.PixelWidth) + yoffset); 
     WB_CroppedImage.Pixels[i] = WB_CapturedImage.Pixels[y * WB_CapturedImage.PixelWidth + x]; 
    } 

    // Set the source of the image control to the new cropped bitmap 
    FinalCroppedImage.Source = WB_CroppedImage;        
} 
else 
{ 
    FinalCroppedImage.Source = null; 
} 
+0

Это '.PixelBuffer' см .: https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.media.imaging.writeablebitmap.pixelbuffer.aspx –

+0

Я также пытался то же решение WB_CroppedImage.Pixels [i] не работает. Любое решение? – Apoorv

ответ

1

Вы должны взглянуть на BitmapEncoder и BitmapDecoder классов.

Также вы, вероятно, сможете использовать BitmapBounds для обрезки изображения - установите «X» и «Y» вместе с «Ширина» и «Высота».

Я думаю, что код может выглядеть следующим образом (но я не проверял):

StorageFile destination; // your destination file 
using (var sourceStream = await sourceFile.OpenAsync(FileAccessMode.Read)) 
{ 
    BitmapDecoder bmpDecoder = await BitmapDecoder.CreateAsync(sourceStream); 
    // here you scale your image if needed and crop by setting X, Y, Width and Height 
    BitmapTransform bmpTransform = new BitmapTransform() { ScaledHeight = scaledHeight, ScaledWidth = scaledWidth, InterpolationMode = BitmapInterpolationMode.Cubic, Bounds = new BitmapBounds { X = topLeftX, Y = topLeftY Width = desiredSizeW, Height = desiredSizeH } }; 
    PixelDataProvider pixelData = await bmpDecoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, bmpTransform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage); 
    using (var destFileStream = await destination.OpenAsync(FileAccessMode.ReadWrite)) 
    { 
     BitmapEncoder bmpEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, destFileStream); 
     // here you need to set height and width - take from above 
     bmpEncoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, desiredSizeW, desiredSizeH, 300, 300, pixelData.DetachPixelData()); 
     await bmpEncoder.FlushAsync(); 
    } 
} 

Конечно вам не нужно, чтобы сохранить отредактированное изображение, чтобы StorageFile - Я использовал в качестве примера вы можете писать в поток, а затем установить источник изображения.

+0

Первой проблемой является MouseLeftButtonUp, MouseLeftButtonDown, MouseMove не поддерживаются в телефоне Windows 8.1. –

+0

@AtifShabeer. Вы спросили об образовании предоставленного изображения, что здесь MouseEvent? Метод выше должен обрезать изображение, но вы должны предоставить информацию как. – Romasz

+0

Я хочу реализовать то же самое в своем приложении: можете ли вы взглянуть на этот учебник по Windows Phone 8.0: http://www.c-sharpcorner.com/uploadfile/55275a/windowsphone-image-crop-with-rectangle/ –