我正在尝试对图像应用过滤器。
XAML:
<Image Name="imageForEditing" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3"
Width="400" Height="400" Stretch="UniformToFill" />
这是我用来从图片库中获取图片的方法:
public async void pickPhoto()
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.Desktop;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".png");
openPicker.FileTypeFilter.Add(".bmp");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
try
{
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
imageForEditing.Source = image;
wbImage = new WriteableBitmap((int)imageForEditing.ActualWidth,(int) imageForEditing.ActualHeight);
wbImage.SetSource(stream);
}
catch (Exception e)
{
MessageDialog msg = new MessageDialog("Greska : " + e.Message);
msg.ShowAsync();
}
}
else
{
(Application.Current as App).isEditorNext = false;
this.Frame.Navigate(typeof(SplashScreen));
}
}
wbImage
是一个全局变量所以,当我尝试在图像上应用效果时,我得到一个异常,说我的值不应该为空。
以下是灰度效果的代码(我甚至不知道它是否有效,我还没有尝试过它)
private WriteableBitmap GrayScale(WriteableBitmap modifiedImage)
{
try
{
int r = 0, a = 0, i = 0;
int h = modifiedImage.PixelHeight;
int w = modifiedImage.PixelWidth;
using (Stream stream = modifiedImage.PixelBuffer.AsStream())
{
byte[] StreamBuffer = new byte[modifiedImage.PixelBuffer.Length];
byte[] tempbuffer = new byte[64000];
stream.Seek(0, 0);
stream.Read(StreamBuffer, 0, StreamBuffer.Length);
for (i = 0; i < StreamBuffer.Length - 4; i = i + 4)
{
var a1 = StreamBuffer[i + 3];
var r1 = StreamBuffer[i + 2];
var g1 = StreamBuffer[i + 1];
var b1 = StreamBuffer[i + 0];
a = 0xff;
r = (byte)((0.311 * r1) + (0.486 * g1) + (0.213 * b1));
StreamBuffer[i + 3] = (byte)a;
StreamBuffer[i + 2] = (byte)(r > 255 ? 255 : (r < 0 ? 0 : r));
StreamBuffer[i + 1] = (byte)(r > 255 ? 255 : (r < 0 ? 0 : r));
StreamBuffer[i + 0] = (byte)(r > 255 ? 255 : (r < 0 ? 0 : r));
}
stream.Seek(0, 0);
stream.Write(StreamBuffer, 0, StreamBuffer.Length);
modifiedImage.Invalidate();
}
}
catch (Exception ex)
{
var exceptionMessageDialog = new Windows.UI.Popups.MessageDialog("Exception : " + ex.Message);
exceptionMessageDialog.ShowAsync();
}
此处抛出异常:
Stream stream = modifiedImage.PixelBuffer.AsStream();
我做错了什么?我已经搜索了超过5个小时的答案。似乎没有任何帮助。
我检查modifiedImage
是否为空,但似乎没问题。以下是调用方法的方法以及我设置imageForEditing.Source
的位置。
wbImage = GrayScale(wbImage);
imageForEditing.Source = wbImage;