两次读取相同的图像流
Posted
技术标签:
【中文标题】两次读取相同的图像流【英文标题】:Reading the Same Image Stream Twice 【发布时间】:2021-06-04 20:50:31 【问题描述】:我想在同一时间或之后获取图像的尺寸并将图像流式传输到对象。 像这样的代码。
string page = pages[pageComboBox.SelectedIndex].pageImage; // image url
var stream = web.OpenRead(page);
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = stream; // First read stream
stream.Position = 0; // tried
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
pageIMG.Source = bitmap;
Image image = Image.FromStream(stream); // Second read stream
MessageBox.Show("Image Height = " + image.Height + " Image Width = " + image.Width);
我确实使用了位置的东西,但它给了我一个错误 -
'此流不支持查找操作。'
请帮忙...
【问题讨论】:
好吧,stream
是什么,它从何而来?事实上,并不是所有的流都可以被搜索到
它只是一个来自 url 的图像。我正在做一个 webscrapper 所以。
这似乎是一个Network
ish 流。你可能不会读两遍。但你可以将它复制到Memory
或FileStream
,然后多次阅读。
所以如果不将其复制到内存中,我就无法像它一样阅读两次?
可以这样直接保存图片。 MemoryStream 流 = new MemoryStream(你的字节数组);图像图像 = Image.FromStream(stream); image.Save("image.bmp");
【参考方案1】:
将源流复制到 MemoryStream:
using (var memoryStream = new MemoryStream())
stream.CopyTo(memoryStream);
memoryStream.Position = 0;
bitmap.BeginInit();
bitmap.StreamSource = memoryStream;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
...
memoryStream.Position = 0;
image = Image.FromStream(memoryStream);
...
但是,将流第二次读入 WinForms 图像似乎毫无意义。您可以改为查询 BitmapImage 的 PixelWidth 和 PixelHeight 属性:
using (var memoryStream = new MemoryStream())
stream.CopyTo(memoryStream);
memoryStream.Position = 0;
bitmap.BeginInit();
bitmap.StreamSource = memoryStream;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
...
MessageBox.Show(
"Image Height = " + bitmap.PixelHeight +
" Image Width = " + bitmap.PixelWidth);
【讨论】:
我做了像素高度,但它们都没有返回真值。它仍然返回 1 高度 1 宽度:S 可能仍然需要复制到 MemoryStream,例如以确保将 Web 响应流读到最后。不记得确切的情况,但我必须这样做一次。 MemoryStream 工作,但我必须在 CopyTo 之后添加memoryStream.Seek(0, SeekOrigin.Begin);stream.Close();
。非常感谢。以上是关于两次读取相同的图像流的主要内容,如果未能解决你的问题,请参考以下文章