Win10 for Phone 裁剪保存

时间:2022-09-26 20:01:24

//StorageFolder savedPics = ApplicationData.Current.LocalFolder;
//BitmapImage bi = new BitmapImage();

//RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
//await renderTargetBitmap.RenderAsync(GridImage);

//IBuffer buffer = await renderTargetBitmap.GetPixelsAsync();
//StorageFile newfile = await savedPics.CreateFileAsync("snap.jpg", CreationCollisionOption.ReplaceExisting);
//using (var writeStream = await newfile.OpenAsync(FileAccessMode.ReadWrite))
//{
// BitmapEncoder jpgencode = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, writeStream);
// byte[] data = buffer.ToArray();

// Rect temp = MeasureUtil.GetBounds(GridImage, LayoutRoot);

// jpgencode.BitmapTransform.Bounds = new BitmapBounds
// {
// X = (uint)Math.Round((measureRect.X - temp.X), 0),
// Y = (uint)Math.Round((measureRect.Y - temp.Y), 0),
// Width = (uint)Math.Round(measureRect.Width, 0),
// Height = (uint)Math.Round(measureRect.Height, 0)
// };

// jpgencode.SetPixelData(
// BitmapPixelFormat.Bgra8,
// BitmapAlphaMode.Straight,
// (uint)renderTargetBitmap.PixelWidth,
// (uint)renderTargetBitmap.PixelHeight,
// 96d, 96d, data);

// bi.SetSource(writeStream);

// // 如果需要设置图片的固定宽、高,可以使用 WriteableBitmap 对象
// //WriteableBitmap wb = new WriteableBitmap(480, 480);
// //wb.SetSource(WriteStream);
// //imgResult.Source = wb;

// await jpgencode.FlushAsync();
//}

RenderTargetBitmap render = new RenderTargetBitmap();
await render.RenderAsync(CroppedImage);

IBuffer pixelBuffer = await render.GetPixelsAsync();

StorageFolder fold = ApplicationData.Current.LocalFolder;
StorageFile file = await fold.CreateFileAsync("save.jpg", CreationCollisionOption.ReplaceExisting);

using (var randstream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, randstream);
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)render.PixelWidth,
(uint)render.PixelHeight,
logicalDpi,
logicalDpi,
pixelBuffer.ToArray());

await encoder.FlushAsync();

}