C# 当图像未存储在本地文件夹中时,更改像素空引用异常
我正在尝试将图像的像素更改为红色,这些图像是从服务器下载的,不存储在本地文件夹中。下面是我正在使用的代码,当图像存储在本地文件夹中时,它工作得非常好C# 当图像未存储在本地文件夹中时,更改像素空引用异常,c#,windows-phone-8,C#,Windows Phone 8,我正在尝试将图像的像素更改为红色,这些图像是从服务器下载的,不存储在本地文件夹中。下面是我正在使用的代码,当图像存储在本地文件夹中时,它工作得非常好 private ImageSource changeimagepixel(string p) { Uri uri = new Uri(p, UriKind.RelativeOrAbsolute); ImageSource imgsource = new BitmapImage(uri);
private ImageSource changeimagepixel(string p)
{
Uri uri = new Uri(p, UriKind.RelativeOrAbsolute);
ImageSource imgsource = new BitmapImage(uri);
image.Source = imgsource;
WriteableBitmap image1 = new WriteableBitmap((BitmapSource)image.Source);
WriteableBitmap image2 = ChangeColor(image1);
image.Source = image2;
return image.Source;
}
public static WriteableBitmap ChangeColor(WriteableBitmap scrBitmap)
{
//You can change your new color here. Red,Green,LawnGreen any..
Color newColor =Colors.Red;
Color actulaColor;
//make an empty bitmap the same size as scrBitmap
WriteableBitmap newBitmap = new WriteableBitmap(scrBitmap.PixelWidth, scrBitmap.PixelHeight);
for (int i = 0; i < scrBitmap.PixelWidth; i++)
{
for (int j = 0; j < scrBitmap.PixelHeight; j++)
{
//get the pixel from the scrBitmap image
actulaColor = scrBitmap.GetPixel(i, j);
// > 150 because.. Images edges can be of low pixel colr. if we set all pixel color to new then there will be no smoothness left.
if (actulaColor.A > 150)
newBitmap.SetPixel(i, j, (Color)newColor);
else
newBitmap.SetPixel(i, j, actulaColor);
}
}
return newBitmap;
}
请任何人提出一个解决方案,以改变像素的图像,这是不在本地文件夹,并从服务器获得
这将是一个很大的帮助
谢谢。在对其进行任何操作之前,您需要等待它完全下载 例如:
public部分类主页:PhoneApplicationPage
{
//建造师
公共主页()
{
初始化组件();
//下载我的dogecoin图像
myImage.Source=新的位图图像(新的Uri(“http://www.chubosaurus.com/dogecoin_wp8.jpg“,UriKind.Absolute”);
//钩住下载完成
myImage.ImageOpened+=bi_ImageOpened;
}
//图像已完全下载,请稍后执行操作
无效bi_图像已打开(对象发送器,路由目标e)
{
//……您的代码
//在这里放一个断点,你会看到它会在图像下载后中断
}
}
如果事件没有触发——很可能是因为您动态创建了
图像
,而没有将其添加到可视化树中,所以要修复此问题,请执行以下操作
//构造函数
公共主页()
{
初始化组件();
Image mytestimage=新图像();
mytestimage.Visibility=System.Windows.Visibility.Collapsed;
mytestimage.Source=新的位图图像(新的Uri(“http://www.chubosaurus.com/dogecoin_wp8.jpg“,UriKind.Absolute”);
//将其作为ContentPanel的子级添加到可视化树中
this.ContentPanel.Children.Add(mytestimage);
//钩住下载完成
mytestimage.ImageOpened+=mytestimage_ImageOpened;
}
//图像已成功下载
void mytestimage_ImageOpened(对象发送方,路由目标)
{
//你的代码
}
是由Thanx@Chubosaurus软件引起的吗。我会尝试更新你。我应该在下面的一行之后添加这个吗?ImageSource imgsource=新的位图图像(uri)@KinjanBhavsar让我编辑解决方案以适合您以前的代码。但它肯定是正确的,您必须等到它被下载。@KinjanBhavsar我更新了解决方案,创建了一个新项目,并逐步完成了代码,您将了解发生了什么。然后用你新学到的知识对你的程序做一些修改。非常感谢。您非常有帮助@Chubosaurus Software是否可以从bi_ImageOpen事件返回image.Source?
WriteableBitmap image1 = new WriteableBitmap((BitmapSource)image.Source);