将位图图像保存到文件
我正在开发一个程序,可以将图像从 URL 下载到位图图像并显示它。接下来,我尝试使用 jpegbitmapencoder 将位图图像保存到硬盘。文件已成功创建,但实际的 jpeg 图像为空或 1 个黑色像素。
public Guid SavePhoto(string istrImagePath)
{
ImagePath = istrImagePath;
BitmapImage objImage = new BitmapImage(
new Uri(istrImagePath, UriKind.RelativeOrAbsolute));
PictureDisplayed.Source = objImage;
savedCreationObject = objImage;
Guid photoID = System.Guid.NewGuid();
string photolocation = photoID.ToString() + ".jpg"; //file name
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(objImage));
using (FileStream filestream = new FileStream(photolocation, FileMode.Create))
{
encoder.Save(filestream);
}
return photoID;
}
这是保存和显示照片的功能。照片显示正确,但在保存时我再次得到一个空的 jpeg 或 1 个黑色像素。
I am working on a program that downloads images from a URL to a bitmapimageand displays it. Next I try to save the bitmapimage to the harddrive using jpegbitmapencoder. The file is successfully created but the actual jpeg image is empty or 1 black pixel.
public Guid SavePhoto(string istrImagePath)
{
ImagePath = istrImagePath;
BitmapImage objImage = new BitmapImage(
new Uri(istrImagePath, UriKind.RelativeOrAbsolute));
PictureDisplayed.Source = objImage;
savedCreationObject = objImage;
Guid photoID = System.Guid.NewGuid();
string photolocation = photoID.ToString() + ".jpg"; //file name
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(objImage));
using (FileStream filestream = new FileStream(photolocation, FileMode.Create))
{
encoder.Save(filestream);
}
return photoID;
}
This is the function that saves and displays the photo. The photo is displayed correctly but again when it is saved I get an empty jpeg or 1 black pixel.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您从 Uri 创建 BitmapImage 时,需要时间来下载图像。
如果您检查以下属性,该值可能为 TRUE。
因此,您可以将侦听器附加到 DownloadCompleted 事件处理程序,并将所有处理移至该 EventHandler。
该处理程序看起来像这样:
您可能还想为 DownloadFailed 添加另一个 EventHandler,以便优雅地处理任何错误情况。
编辑
根据本的评论添加了完整的示例类:
When you create your BitmapImage from a Uri, time is required to download the image.
If you check the following property, the value will likely be TRUE
As such, you much attach a listener to the DownloadCompleted event handler and move all processing to that EventHandler.
Where that handler will look something like:
You will likely also want to add another EventHandler for DownloadFailed in order to gracefully handle any error cases.
Edit
Added full sample class based on Ben's comment:
扩展了 Chris Baxter 的解决方案,此转换器使用本地版本(如果存在),否则下载并保存文件。
并确保您可以在 xaml 中访问转换器
并在图像上使用转换器
Expanding on Chris Baxter's solution, this Converter uses the local version if it exists, otherwise downloads it and saves the file.
And make sure you can access the converter within your xaml
And use the converter on an image