我正在尝试将图像的像素更改为红色,图像从服务器下载并且不存储在本地文件夹中。我正在使用以下代码,当图像存储在本地文件夹中时,它可以正常工作。
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;
}
此处, p 是从服务器获取的图片的网址,我在
获得 NullReference异常WriteableBitmap image1 = new WriteableBitmap((BitmapSource)image.Source);
请有人建议解决方案,更改不在本地文件夹中并从服务器获取的图像像素。
这将是一个很大的帮助。
感谢。
答案 0 :(得分:0)
在对其进行任何操作之前,您需要等待它完全下载。
示例:
<Grid x:Name="ContentPanel">
<Image x:Name="myImage"></Image>
</Grid>
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// download my dogecoin image
myImage.Source = new BitmapImage(new Uri("http://www.chubosaurus.com/dogecoin_wp8.jpg", UriKind.Absolute));
// hook the download complete
myImage.ImageOpened += bi_ImageOpened;
}
// image has downloaded completely, do your actions afterwards
void bi_ImageOpened(object sender, RoutedEventArgs e)
{
// ..... your code
// put a break point here, you will see it will break when the image has downloaded
}
}
如果事件未触发 - 很可能是因为您动态创建了Image
而未将其添加到Visual Tree中,所以要解决此问题,请执行以下操作
<!-- the default ContentPanel when creating the project -->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<!--- your content -->
</Grid>
// Constructor
public MainPage()
{
InitializeComponent();
Image mytestimage = new Image();
mytestimage.Visibility = System.Windows.Visibility.Collapsed;
mytestimage.Source = new BitmapImage(new Uri("http://www.chubosaurus.com/dogecoin_wp8.jpg", UriKind.Absolute));
// add it to the Visual Tree as a child of ContentPanel
this.ContentPanel.Children.Add(mytestimage);
// hook the download complete
mytestimage.ImageOpened += mytestimage_ImageOpened;
}
// image has been downloaded successfully
void mytestimage_ImageOpened(object sender, RoutedEventArgs e)
{
// your code
}