0
我正在從CameraCaptureTask獲取圖像,並且希望能夠在保存前使圖像變得更小。寬度和高度自動設置爲最高分辨率,這比我需要的多得多。我一直在嘗試獲取圖像,更改尺寸,然後嘗試保存,儘管我遇到了錯誤。如何更改圖像的大小
ORIGINAL
MainPage.xaml.cs中
private void cameraTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BitmapImage bmi = new BitmapImage();
bmi.SetSource(e.ChosenPhoto);
//MessageBox.Show(bmi.PixelWidth.ToString() + "x" + bmi.PixelHeight.ToString());
var gcd = GCD(bmi.PixelWidth, bmi.PixelHeight);
var result = string.Format("{0}:{1}", bmi.PixelWidth/gcd, bmi.PixelHeight/gcd);
WriteableBitmap wb;
Stream stream;
switch (result)
{
case "3:4":
wb = new WriteableBitmap(480,640);
break;
case "4:3":
wb = new WriteableBitmap(640,480);
break;
case "9:16":
wb = new WriteableBitmap(448, 800);
break;
case "16:9":
wb = new WriteableBitmap(800, 448);
break;
default:
wb = null;
return;
}
//Set the wb to the original stream?
wb.SetSource(e.ChosenPhoto);
//Convert the wb to a stream for saving
stream = new MemoryStream(wb.ToByteArray());
//Need to replace the following line with the new image stream for saving?
//var capturedPicture = new CapturedPicture(e.OriginalFileName, e.ChosenPhoto);
var capturedPicture = new CapturedPicture(e.OriginalFileName, stream);
}
}
public int GCD(int a, int b)
{
while (a != 0 && b != 0)
{
if (a > b)
a %= b;
else
b %= a;
}
if (a == 0)
return b;
else
return a;
}
編輯:新實現
private void cameraTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BitmapImage bmi = new BitmapImage();
bmi.SetSource(e.ChosenPhoto);
var gcd = GCD(bmi.PixelWidth, bmi.PixelHeight);
var result = string.Format("{0}:{1}", bmi.PixelWidth/gcd, bmi.PixelHeight/gcd);
WriteableBitmap wb = new WriteableBitmap(bmi);
Stream stream = new MemoryStream();
switch (result)
{
case "3:4":
wb.SaveJpeg(stream, 480, 640, 0, 100);
break;
case "4:3":
wb.SaveJpeg(stream, 640, 480, 0, 100);
break;
case "9:16":
wb.SaveJpeg(stream, 448, 800, 0, 100);
break;
case "16:9":
wb.SaveJpeg(stream, 800, 448, 0, 100);
break;
default:
wb = null;
return;
}
stream.Seek(0, SeekOrigin.Begin);
//var capturedPicture = new CapturedPicture(e.OriginalFileName, e.ChosenPhoto);
var capturedPicture = new CapturedPicture(e.OriginalFileName, stream);
我怎樣才能從新圖像創建一個流'var capturedPicture = new CapturedPicture(e.OriginalFileName,i);''其中'i'是流?需要注意的是,'CapturedPicture'是一個類,它需要圖像名稱和結果流將圖像保存到'IsolatedStorage'。 – Matthew
此外,我爲Windows Phone使用.Net 4.5,並且「Bitmap」不存在,這就是我使用「BitmapImage」和「WriteableBitmap」的原因。 – Matthew
我稍微更改了我的實現,直接將具有新大小的'WriteableBitmap'分配給原始流結果'e.ChosenPhoto',但發生了一個新錯誤,說明使用了未分配的局部變量wb''? – Matthew