gpt4 book ai didi

c# - 在 WP8 中从 Web URL 加载图像

转载 作者:行者123 更新时间:2023-11-30 22:09:02 25 4
gpt4 key购买 nike

我有一张指定网址的网页图片,可以在浏览器中浏览。

我试图从 web url 检索它,当程序转到 bitmapImage.SetSource(ms); 我得到一个异常“

ex = {System.Exception: The component cannot be found. (Exception from HRESULT: 0x88982F50)
at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
at MS.Internal.XcpImports.BitmapSource_SetSource(BitmapSource bitmapSource, CValue& byteStream)
at System.Wi...

"我确实在 stackoverflow 上搜索了其他问题……但对此没有帮助。谁能帮帮我?

byte数组确实有数据,运行时调试返回imageByteArray = {byte[1227]};我的选择是将字节数组转换为 BitmapImage 时发生异常。

在 httpclient 包装器类中:

public static async Task<Byte[]> GetWebImageByImageName(string ImageName)
{
//Uri imageServerUril = new Uri(ImageName);

var requestMessage = new HttpRequestMessage(HttpMethod.Get, ImageName);
var responseMessage = await client.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead);

var responseData = await responseMessage.Content.ReadAsByteArrayAsync();
return responseData;

}

在 View 模型中:

private async void ReadArticleList(int pageNumber)
{
string webURL = "http://....."; // the web URL is no problem
try
{
byte[] imageByteArray = await CollectionHttpClient.GetWebImageByImageName(webURL);//


//Convert it to BitmapImage
using (MemoryStream ms = new MemoryStream(imageByteArray))
{
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.CreateOptions = BitmapCreateOptions.DelayCreation;
bitmapImage.SetSource(ms); // the exception got here
item.BitImage = bitmapImage;
}



IsLoading = false;


}
catch(Exception ex)
{
if (ex.HResult == -2146233088 && ex.Message.Equals("Response status code does not indicate success: 404 ()."))
{
MessageBox.Show("The network is not set right. Internet cannot be accessed.");
}
else
{
MessageBox.Show("sorry, no data.");
}

IsLoading = false;
}

}

* 用于详细信息 *

  1. BitImage 是 BitmapImage 的实例;
  2. item.BitImage: item 是 Article 的一个实例
  3. 图片格式为JPEG

文章模型如下:

public class Article : INotifyPropertyChanged
{
private long _Id;
public long ID
{
get { return _Id; }
set
{
if (_Id != value)
{
_Id = value;
NotifyPropertyChanged("ID");
}
}
}


private string _subject;
public string Subject
{
get
{
return _subject;
}
set
{
if (_subject != value)
{
_subject = value;
NotifyPropertyChanged("Subject");
}
}
}

private string _words;
public string Words
{
get
{
return _words;
}
set
{
if (_words != value)
{
_words = value;
NotifyPropertyChanged("Words");
}
}
}

private DateTime _publishDate;
public DateTime PublishDate
{
get
{ return _publishDate; }
set
{
if (_publishDate != value)
{
_publishDate = value;
NotifyPropertyChanged("PublishDate");
}
}
}

public List<string> ImagePathList = new List<string>();

public BitmapImage BitImage = new BitmapImage();

private string _firstImage;
public string FirstImage
{
get
{
return _firstImage;
}
set
{
if (_firstImage != value)
{
_firstImage = value;
NotifyPropertyChanged();
}
}
}

public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}

最佳答案

如果您只想显示来自远程服务器的图像而不保存它,请执行以下操作:

imageControl1.Source = new BitmapImage(new Uri("http://delisle.saskatooncatholic.ca/sites/delisle.saskatooncatholic.ca/files/sample-1.jpg", UriKind.Absolute));

如果要将图像保存到 IsolatedStorage,可以执行以下操作:

WebClient webClientImg = new WebClient();
webClientImg.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
webClientImg.OpenReadAsync(new Uri("http://delisle.saskatooncatholic.ca/sites/delisle.saskatooncatholic.ca/files/sample-1.jpg", UriKind.Absolute));

void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
isSpaceAvailable = IsSpaceIsAvailable(e.Result.Length);
if (isSpaceAvailable)
{
SaveToJpeg(e.Result);
}
else
{
MessageBox.Show("You are running low on storage space on your phone. Hence the image will be loaded from the internet and not saved on the phone.", "Warning", MessageBoxButton.OK);
}
}

检查IsolatedStorage空间是否可用的功能,否则将不会下载图像。

    private bool IsSpaceIsAvailable(long spaceReq)
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
long spaceAvail = store.AvailableFreeSpace;
if (spaceReq > spaceAvail)
{
return false;
}
return true;
}
}

如果空间可用,使用以下函数将图像保存到 IsolatedStorage:

    private void SaveToJpeg(Stream stream)
{
using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isostream = iso.CreateFile("image1.jpg"))
{
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(stream);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, isostream, wb.PixelWidth, wb.PixelHeight, 0, 85);
isostream.Close();

LoadImageFromIsolatedStorage(); //Load recently saved image into the image control
}
}
}

从 IsolatedStorage 加载图像到图像控件中:

    private void LoadImageFromIsolatedStorage()
{
byte[] data;

try
{
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs = isf.OpenFile("image1.jpg", FileMode.Open, FileAccess.Read))
{
data = new byte[isfs.Length];
isfs.Read(data, 0, data.Length);
isfs.Close();
}
}
MemoryStream ms = new MemoryStream(data);
BitmapImage bi = new BitmapImage();
bi.SetSource(ms);
imageControl1.Source = bi;
}
catch
{
}
}

Image taken randomly from Google Search. Credits to the image lie to the owner.

希望这对您有所帮助。 :)

关于c# - 在 WP8 中从 Web URL 加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21845820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com