我在创建一个BitmapImage来自MemoryStreamweb请求的png和gif字节时遇到了一些麻烦.这些字节似乎可以很好地下载,并且BitmapImage创建的对象没有问题,但是图像实际上并没有在我的UI上呈现.仅当下载的图像是png或gif类型时才会出现此问题(适用于jpeg).
以下是演示此问题的代码:
var webResponse = webRequest.GetResponse();
var stream = webResponse.GetResponseStream();
if (stream.CanRead)
{
Byte[] buffer = new Byte[webResponse.ContentLength];
stream.Read(buffer, 0, buffer.Length);
var byteStream = new System.IO.MemoryStream(buffer);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.DecodePixelWidth = 30;
bi.StreamSource = byteStream;
bi.EndInit();
byteStream.Close();
stream.Close();
return bi;
}
Run Code Online (Sandbox Code Playgroud)
为了测试Web请求是否正确获取字节,我尝试了以下操作,将字节保存到磁盘上的文件,然后使用a UriSource而不是a 加载图像StreamSource,它适用于所有图像类型:
var webResponse = webRequest.GetResponse();
var stream = webResponse.GetResponseStream();
if (stream.CanRead)
{
Byte[] buffer = new Byte[webResponse.ContentLength];
stream.Read(buffer, 0, buffer.Length);
string fName = "c:\\" + …Run Code Online (Sandbox Code Playgroud) 美好的一天,
我在使用图像权限时遇到了一些麻烦.
我正在从文件加载图像,调整大小,然后将其保存到另一个文件夹.然后我就这样显示:
uriSource = new Uri(Combine(imagesDirectoryTemp, generatedFileName), UriKind.Absolute);
imgAsset.Source = new BitmapImage(uriSource);
Run Code Online (Sandbox Code Playgroud)
这工作正常,如果用户然后立即选择另一个图像并尝试将其保存在原始文件上,则会出现问题.
保存图像时会生成异常 "ExternalException: A generic error occurred in GDI+."
在一些游戏后,我已经将错误缩小到imgAsset.Source = new BitmapImage(uriSource);删除此行并且不设置imagesource将允许我多次覆盖此文件.
我还尝试将源设置为其他内容,然后重新保存,希望旧的引用将被处理,情况并非如此.
我怎么能通过这个错误?
谢谢,Kohan
编辑
现在使用此代码我没有得到异常,但图像源没有更新.此外,因为我没有使用SourceStream,我不知道我需要处理什么才能使这个工作.
uriSource = new Uri(Combine(imagesDirectoryTemp, generatedFileName), UriKind.Absolute);
imgTemp = new BitmapImage();
imgTemp.BeginInit();
imgTemp.CacheOption = BitmapCacheOption.OnLoad;
imgTemp.UriSource = uriSource;
imgTemp.EndInit();
imgAsset.Source = imgTemp;
Run Code Online (Sandbox Code Playgroud) 这似乎是一个相当简单的问题,但我似乎无法想办法解决它.
在WPF窗口中,我有一个图像image_small_pic.在关联的C#文件中,我使用以下代码设置了它的值:
Uri src = new Uri(image_source, UriKind.RelativeOrAbsolute);
small_image_bmp = new BitmapImage(src);
image_small_pic.Source = small_image_bmp;
Run Code Online (Sandbox Code Playgroud)
其中small_image_bmp是一个公共的BitmapImage对象.但是如果那时候,如果我将small_image_bmp更改为另一个文件并重新分配image_small_pic.Source,那么原始图像仍然被锁定,我无法删除它.即使我稍后尝试它仍然被锁定.有什么想法我可以解决这个问题吗?